freshyo/apps/admin-ui/tests/pages/complaints.test.tsx
2026-10-20 11:19:25 +05:30

331 lines
11 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 14.1 — Complaints (`tests/pages/complaints.test.tsx`).
*
* The complaints fixture is DB-shaped; the `admin.complaint.getAll` procedure
* flattens each row to {text, userName, userMobile, status, images, response}.
* Tests build that page shape locally (see COMPLAINT_PAGE_*).
*
* The real `useInfiniteQuery` runs here: retry/focus/resolve refetches are
* observed through the recorded procedure calls, and ACOMPUI-13 serves a real
* second page (cursor) so `fetchNextPage` appends through the real hook.
*/
import React from 'react'
import { Alert, FlatList, Image, Modal, RefreshControl } from 'react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native'
import Complaints from '@/app/(drawer)/dashboard/complaints/index'
import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import {
lastMutationInput,
procedureMutationCalls,
procedureQueryCalls,
setProcedure,
} from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock'
// Focus simulation: the shared @react-navigation mock never re-runs the focus
// effect, so `useMarkDataFetchers` can never be observed. This local mock keeps
// the real module and adds a manual `__triggerFocus`.
jest.mock('@react-navigation/native', () => {
const actual = jest.requireActual('@react-navigation/native')
const ReactActual = jest.requireActual('react')
const listeners = new Set<() => void>()
const useFocusEffect = (callback: () => void | (() => void)) => {
ReactActual.useEffect(() => {
const run = () => {
callback()
}
listeners.add(run)
run()
return () => {
listeners.delete(run)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback])
}
return {
...actual,
useFocusEffect,
__triggerFocus: () => listeners.forEach((listener) => listener()),
}
})
const navMock = require('@react-navigation/native') as any
const COMPLAINT = (over: Record<string, any> = {}) => ({
id: 1,
userId: 5,
userName: 'Test User',
userMobile: '9876543210',
orderId: 11,
regionId: 1,
text: 'Late delivery',
status: 'pending',
images: [] as string[],
response: null as string | null,
createdAt: new Date().toISOString(),
...over,
})
const COMPLAINT_PENDING = COMPLAINT()
const COMPLAINT_RESOLVED = COMPLAINT({
id: 2,
orderId: null,
text: 'App issue',
status: 'resolved',
images: ['issue.jpg'],
response: 'We fixed it',
})
function setComplaintPage(page: { complaints: any[]; nextCursor?: number }) {
setProcedure('admin.complaint.getAll', { data: page })
}
/** Page through the same procedure: page 1 has a cursor, page 2 does not. */
function setPagedComplaints() {
setProcedure('admin.complaint.getAll', {
impl: (input: any) => {
if (input?.cursor) {
return { complaints: [COMPLAINT_PENDING, COMPLAINT_RESOLVED], nextCursor: undefined }
}
return { complaints: [COMPLAINT_PENDING], nextCursor: 1 }
},
})
}
function queryCallCount() {
return procedureQueryCalls('admin.complaint.getAll').length
}
function renderComplaints() {
return renderAndFlush(<Complaints />, { auth: 'in' })
}
describe('Complaints (ACOMPUI-01..16)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
})
afterEach(() => alertSpy?.mockRestore())
it('ACOMPUI-01: shows "Loading complaints..." while the query is pending', () => {
setProcedure('admin.complaint.getAll', { mode: 'pending' })
const view = renderWithProviders(<Complaints />, { auth: 'in' })
expect(view.getByText('Loading complaints...')).toBeTruthy()
})
it('ACOMPUI-02: a failed query shows Error + Retry and Retry refetches', async () => {
setProcedure('admin.complaint.getAll', { mode: 'error', error: new Error('boom') })
const view = await renderComplaints()
expect(view.getByText('Error')).toBeTruthy()
expect(view.getByText('boom')).toBeTruthy()
const calls = queryCallCount()
fireEvent.press(view.getByText('Retry'))
await waitFor(() => expect(queryCallCount()).toBe(calls + 1))
})
it('ACOMPUI-03: an empty page renders the empty copy', async () => {
setComplaintPage({ complaints: [] })
const view = await renderComplaints()
expect(view.getByText('No complaints')).toBeTruthy()
expect(view.getByText('All complaints will appear here')).toBeTruthy()
})
it('ACOMPUI-04: a card shows id, user, order, text, status, images and response', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING, COMPLAINT_RESOLVED] })
const view = await renderComplaints()
expect(view.getByText('Complaint #1')).toBeTruthy()
expect(view.getByText('Late delivery')).toBeTruthy()
expect(view.getAllByText('Test User').length).toBeGreaterThanOrEqual(1)
expect(view.getByText('Order #11')).toBeTruthy()
expect(view.getByText('Pending')).toBeTruthy()
expect(view.getByText('Attached Images:')).toBeTruthy()
expect(view.getByText('App issue')).toBeTruthy()
expect(view.getByText('Resolved')).toBeTruthy()
expect(view.getByText('Admin Reply')).toBeTruthy()
expect(view.getByText('We fixed it')).toBeTruthy()
expect(view.UNSAFE_getAllByType(Image).some((image) => image.props.source?.uri === 'issue.jpg')).toBe(true)
})
it('ACOMPUI-05: a pending complaint shows the Pending status + resolve button', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = await renderComplaints()
expect(view.getByText('Pending')).toBeTruthy()
expect(view.getByText('Resolve Complaint')).toBeTruthy()
})
it('ACOMPUI-06: a resolved complaint shows the Resolved status and hides resolve', async () => {
setComplaintPage({ complaints: [COMPLAINT_RESOLVED] })
const view = await renderComplaints()
expect(view.getByText('Resolved')).toBeTruthy()
expect(view.queryByText('Resolve Complaint')).toBeNull()
})
it('ACOMPUI-07: pressing the user opens the user detail route', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = await renderComplaints()
fireEvent.press(view.getByText('Test User'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
})
it('ACOMPUI-08: pressing the order opens the order detail route', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = await renderComplaints()
fireEvent.press(view.getByText('Order #11'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders/order-details/11')
})
it('ACOMPUI-09: Mark resolved opens the confirmation dialog with a comment field', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = await renderComplaints()
fireEvent.press(view.getByText('Resolve Complaint'))
expect(view.getByText('Add admin notes for this resolution:')).toBeTruthy()
expect(view.getByPlaceholderText('Add a comment...')).toBeTruthy()
expect(view.getByText('Resolve')).toBeTruthy()
expect(view.getByText('Cancel')).toBeTruthy()
})
it('ACOMPUI-10: an empty comment still submits (server min(1) is the only guard)', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = await renderComplaints()
fireEvent.press(view.getByText('Resolve Complaint'))
fireEvent.press(view.getByText('Resolve'))
await waitFor(() =>
expect(lastMutationInput('admin.complaint.resolve')).toEqual({ id: '1', response: '' })
)
expect(procedureMutationCalls('admin.complaint.resolve')).toHaveLength(1)
})
it('ACOMPUI-11: resolving sends the comment, alerts success and refetches', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = await renderComplaints()
const calls = queryCallCount()
fireEvent.press(view.getByText('Resolve Complaint'))
fireEvent.changeText(view.getByPlaceholderText('Add a comment...'), 'Fixed')
fireEvent.press(view.getByText('Resolve'))
await waitFor(() =>
expect(lastMutationInput('admin.complaint.resolve')).toEqual({ id: '1', response: 'Fixed' })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Complaint marked as resolved')
)
await waitFor(() => expect(queryCallCount()).toBeGreaterThan(calls))
expect(view.queryByText('Add admin notes for this resolution:')).toBeNull()
})
it('ACOMPUI-12: a failed resolve alerts the error and closes the dialog', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
setProcedure('admin.complaint.resolve', { mode: 'error', error: new Error('nope') })
const view = await renderComplaints()
fireEvent.press(view.getByText('Resolve Complaint'))
fireEvent.changeText(view.getByPlaceholderText('Add a comment...'), 'Fixed')
fireEvent.press(view.getByText('Resolve'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope'))
await waitFor(() =>
expect(view.queryByText('Add admin notes for this resolution:')).toBeNull()
)
})
it('ACOMPUI-13: end of list calls fetchNextPage and the appended page is rendered', async () => {
setPagedComplaints()
const view = await renderComplaints()
expect(view.getByText('Complaint #1')).toBeTruthy()
const list = view.UNSAFE_getByType(FlatList)
await act(async () => {
await list.props.onEndReached?.({ distanceFromEnd: 0 })
})
// The real infinite query requested the next page with the cursor.
await waitFor(() => expect(queryCallCount()).toBeGreaterThanOrEqual(2))
const calls = procedureQueryCalls('admin.complaint.getAll')
expect(calls[calls.length - 1]).toMatchObject({ limit: 20, cursor: 1 })
await waitFor(() => expect(view.getByText('Complaint #2')).toBeTruthy())
expect(view.getByText('Complaint #1')).toBeTruthy()
})
it('ACOMPUI-14: pull-to-refresh triggers the shared refresh (query cache clear)', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = await renderComplaints()
const clearSpy = jest.spyOn(view.queryClient, 'clear')
const refresh = view.UNSAFE_getByType(RefreshControl)
await act(async () => {
refresh.props.onRefresh?.()
})
expect(clearSpy).toHaveBeenCalled()
})
it('ACOMPUI-15: the marked data fetcher refetches on the next focus', async () => {
setComplaintPage({ complaints: [COMPLAINT_PENDING] })
await renderComplaints()
// Only the initial fetch so far: the focus hook skips its first pass.
expect(queryCallCount()).toBe(1)
await act(async () => {
navMock.__triggerFocus()
})
await waitFor(() => expect(queryCallCount()).toBeGreaterThan(1))
})
it('ACOMPUI-16: pressing an attached image opens the image viewer', async () => {
setComplaintPage({ complaints: [COMPLAINT_RESOLVED] })
const view = await renderComplaints()
const image = view
.UNSAFE_getAllByType(Image)
.find((node) => node.props.source?.uri === 'issue.jpg')
expect(image).toBeTruthy()
fireEvent.press(image as any)
await waitFor(() => {
expect(view.UNSAFE_getAllByType(Modal).some((modal) => modal.props.visible === true)).toBe(true)
})
})
})