/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Catalogue section 14.4 — User detail (`tests/pages/user-detail.test.tsx`). * * The incidents fixture is DB-shaped (addedBy is an object); the component * renders `addedBy` directly, so tests feed the procedure-shaped value. * The shared trpc mock's `refetch` is not observable, so this file wraps the * same registry locally to expose it (no harness file is modified). */ import React from 'react' import { ActivityIndicator, Alert, StyleSheet } from 'react-native' import { act, fireEvent } from '@testing-library/react-native' import { tw } from 'common-ui' import UserDetails from '@/app/(drawer)/dashboard/user-management/[id]' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { lastMutationInput, procedureQueryCalls, setProcedure } from '../mocks/trpc-client' import { router, __setParams } from '../mocks/expo-router-mock' import { USER_DETAILS } from '../fixtures' jest.mock('../mocks/trpc-client', () => { const actual = jest.requireActual('../mocks/trpc-client') const refetch = jest.fn(async () => ({ data: undefined })) const nodeFor = (path: string) => path.split('.').reduce((node: any, key: string) => node[key], actual.trpc) const wrap = (path: string): any => new Proxy( {}, { get(_target, prop) { if (typeof prop !== 'string') return undefined if ( !path && (prop === 'Provider' || prop === 'createClient' || prop === 'useUtils' || prop === 'useContext') ) { return actual.trpc[prop] } if (prop === 'useQuery' && path === 'admin.user.getUserDetails') { return (input: any, options: any) => ({ ...nodeFor(path).useQuery(input, options), refetch, }) } if (prop === 'useQuery' || prop === 'useMutation' || prop === 'useInfiniteQuery') { return nodeFor(path)[prop] } return wrap(path ? `${path}.${prop}` : prop) }, } ) return { ...actual, trpc: wrap(''), __refetch: refetch } }) const trpcMock = require('../mocks/trpc-client') as any const NOW = new Date().toISOString() const ORDER_SUMMARY = (over: Record = {}) => ({ id: 11, readableId: 101, totalAmount: '445', createdAt: NOW, status: 'pending', isFlashDelivery: false, itemCount: 2, ...over, }) const INCIDENT = { id: 1, userId: 5, orderId: 11, dateAdded: NOW, adminComment: 'Late delivery', addedBy: 'Admin One', negativityScore: 2, orderStatus: 'active', } function setDetails(over: Record = {}) { setProcedure('admin.user.getUserDetails', { data: { user: { ...USER_DETAILS, ...(over.user ?? {}) }, orders: over.orders ?? [ORDER_SUMMARY()], }, }) } function renderDetails() { return renderWithProviders(, { auth: 'in' }) } describe('User detail (AUD-01..17)', () => { let alertSpy: jest.SpyInstance beforeEach(() => { resetAllMocks() alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) __setParams({ id: '5' }) // Avoid the DB-shaped incident fixture (addedBy object) for non-incident rows. setProcedure('admin.user.getUserIncidents', { data: { incidents: [] } }) }) afterEach(() => alertSpy?.mockRestore()) it('AUD-01: shows "Loading user details..." while the query is pending', () => { setProcedure('admin.user.getUserDetails', { mode: 'pending' }) const view = renderDetails() expect(view.getByText('Loading user details...')).toBeTruthy() }) it('AUD-02: a failed query shows Error + Retry and Retry refetches', async () => { setProcedure('admin.user.getUserDetails', { mode: 'error', error: new Error('boom') }) const view = renderDetails() await flush() expect(view.getByText('Error')).toBeTruthy() expect(view.getByText('boom')).toBeTruthy() fireEvent.press(view.getByText('Retry')) expect(trpcMock.__refetch).toHaveBeenCalled() }) it('AUD-03: an invalid id disables the query and shows the error state', async () => { __setParams({}) const view = renderDetails() await flush() expect(view.getByText('Failed to load user details')).toBeTruthy() expect(view.getByText('Retry')).toBeTruthy() expect(procedureQueryCalls('admin.user.getUserDetails')).toHaveLength(0) }) it('AUD-04: the header shows mobile, name and registration date', async () => { setDetails() const view = renderDetails() await flush() expect(view.getByText('User Details')).toBeTruthy() expect(view.getByText('9876543210')).toBeTruthy() expect(view.getByText('Test User')).toBeTruthy() expect(view.getByText(/^Registered /)).toBeTruthy() }) it('AUD-05: missing name and mobile use the fallbacks', async () => { setDetails({ user: { name: null, mobile: null } }) const view = renderDetails() await flush() expect(view.getByText('Unnamed User')).toBeTruthy() expect(view.getByText('No Mobile')).toBeTruthy() }) it('AUD-06: a suspended user shows the Suspended badge', async () => { setDetails({ user: { isSuspended: true } }) const view = renderDetails() await flush() expect(view.getByText('Suspended')).toBeTruthy() }) it('AUD-07: toggling suspension sends the mutation and refetches', async () => { setDetails() const view = renderDetails() await flush() fireEvent.press(view.getByRole('checkbox')) await flush(2) expect(lastMutationInput('admin.user.updateUserSuspension')).toEqual({ userId: 5, isSuspended: true, }) expect(trpcMock.__refetch).toHaveBeenCalled() }) it('AUD-08: a pending suspension swap shows a spinner instead of the checkbox', async () => { setDetails() setProcedure('admin.user.updateUserSuspension', { mode: 'pending' }) const view = renderDetails() await flush() fireEvent.press(view.getByRole('checkbox')) await flush(2) expect(view.queryByRole('checkbox')).toBeNull() expect(view.UNSAFE_getAllByType(ActivityIndicator).length).toBeGreaterThanOrEqual(1) }) it('AUD-09: a failed suspension is silent (no alert) — current gap', async () => { setDetails() setProcedure('admin.user.updateUserSuspension', { mode: 'error', error: new Error('nope') }) const view = renderDetails() await flush() fireEvent.press(view.getByRole('checkbox')) await flush(3) expect(lastMutationInput('admin.user.updateUserSuspension')).toEqual({ userId: 5, isSuspended: true, }) expect(alertSpy).not.toHaveBeenCalled() expect(view.getByRole('checkbox')).toBeTruthy() }) it('AUD-10: the incidents section renders its rows for the user', async () => { setDetails() setProcedure('admin.user.getUserIncidents', { data: { incidents: [INCIDENT] } }) const view = renderDetails() await flush() expect(view.getByText('User Incidents')).toBeTruthy() expect(view.getByText('Late delivery')).toBeTruthy() expect(view.getByText('Added by Admin One')).toBeTruthy() expect(view.getByText('Score: 2')).toBeTruthy() expect(view.getByText('Order #11')).toBeTruthy() }) it('AUD-11: order history shows the count and cards', async () => { setDetails({ orders: [ ORDER_SUMMARY(), ORDER_SUMMARY({ id: 13, readableId: 103, status: 'delivered' }), ], }) const view = renderDetails() await flush() expect(view.getByText('Order History')).toBeTruthy() expect(view.getByText('2 orders')).toBeTruthy() expect(view.getByText('#101')).toBeTruthy() expect(view.getByText('#103')).toBeTruthy() expect(view.getAllByText('₹445')).toHaveLength(2) expect(view.getByText('pending')).toBeTruthy() expect(view.getByText('delivered')).toBeTruthy() }) it('AUD-12: no orders shows "No orders yet" and a zero count', async () => { setDetails({ orders: [] }) const view = renderDetails() await flush() expect(view.getByText('0 orders')).toBeTruthy() expect(view.getByText('No orders yet')).toBeTruthy() }) it('AUD-13: pressing an order opens the order detail route', async () => { setDetails() const view = renderDetails() await flush() fireEvent.press(view.getByText('#101')) expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders/order-details/11') }) it('AUD-14: delivered / cancelled / pending statuses use their colors', async () => { setDetails({ orders: [ ORDER_SUMMARY({ id: 11, readableId: 101, status: 'delivered' }), ORDER_SUMMARY({ id: 12, readableId: 102, status: 'cancelled' }), ORDER_SUMMARY({ id: 13, readableId: 103, status: 'pending' }), ], }) const view = renderDetails() await flush() const colorOf = (status: string) => StyleSheet.flatten(view.getByText(status).props.style).color expect(colorOf('delivered')).toBe((tw`text-green-600` as any).color) expect(colorOf('cancelled')).toBe((tw`text-red-600` as any).color) expect(colorOf('pending')).toBe((tw`text-yellow-600` as any).color) }) it('AUD-15: a flash order shows the ⚡ badge', async () => { setDetails({ orders: [ORDER_SUMMARY({ isFlashDelivery: true })] }) const view = renderDetails() await flush() expect(view.getByText('⚡')).toBeTruthy() }) it('AUD-16: item counts use singular and plural copy', async () => { setDetails({ orders: [ ORDER_SUMMARY({ id: 11, readableId: 101, itemCount: 1 }), ORDER_SUMMARY({ id: 12, readableId: 102, itemCount: 2 }), ], }) const view = renderDetails() await flush() expect(view.getByText('1 item')).toBeTruthy() expect(view.getByText('2 items')).toBeTruthy() }) it('AUD-17: the back button calls router.back', async () => { setDetails() const view = renderDetails() await flush() fireEvent.press(view.getByTestId('user-detail-back')) expect(router.back).toHaveBeenCalled() }) })