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

306 lines
9.9 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 14.3 — User management (`tests/pages/user-management.test.tsx`).
*
* The real tRPC client + React Query run here; `setUsersPages` feeds the
* infinite query one page per `cursor` through the network mock.
*/
import React from 'react'
import { ActivityIndicator, RefreshControl, StyleSheet } from 'react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native'
import { tw } from 'common-ui'
import UserManagement from '@/app/(drawer)/dashboard/user-management/index'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { procedureQueryCalls, setProcedure } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock'
import { USER_1, USER_NO_NAME, USER_SUSPENDED } from '../fixtures'
type Page = { users: any[]; nextCursor?: number }
function setUsersPages(pages: Page[]) {
setProcedure('admin.user.getAllUsers', {
impl: (input: any) => {
const cursor = input?.cursor
if (cursor === undefined || cursor === null) return pages[0] ?? { users: [] }
const index = pages.slice(0, -1).findIndex((page) => page.nextCursor === cursor)
return pages[index + 1] ?? { users: [] }
},
})
}
function renderUsers() {
return renderWithProviders(<UserManagement />, { auth: 'in' })
}
function list(view: ReturnType<typeof renderUsers>) {
return view.UNSAFE_getAllByType(require('react-native').FlatList)[0]
}
async function loadNextPage(view: ReturnType<typeof renderUsers>) {
await act(async () => {
list(view).props.onEndReached?.({ distanceFromEnd: 0 })
})
await flush()
}
describe('User management (AUM-01..18)', () => {
beforeEach(() => resetAllMocks())
it('AUM-01: shows "Loading users..." while the first page is pending', () => {
setProcedure('admin.user.getAllUsers', { mode: 'pending' })
const view = renderUsers()
expect(view.getByText('Loading users...')).toBeTruthy()
})
it('AUM-02: a failed query shows Error + Retry and Retry refetches', async () => {
setProcedure('admin.user.getAllUsers', { mode: 'error', error: new Error('boom') })
const view = renderUsers()
await flush()
expect(view.getByText('Error')).toBeTruthy()
expect(view.getByText('boom')).toBeTruthy()
const before = procedureQueryCalls('admin.user.getAllUsers').length
fireEvent.press(view.getByText('Retry'))
await waitFor(() => {
expect(procedureQueryCalls('admin.user.getAllUsers').length).toBeGreaterThan(before)
})
})
it('AUM-03: an empty list shows "No users found"', async () => {
setUsersPages([{ users: [] }])
const view = renderUsers()
await flush()
expect(view.getByText('No users found')).toBeTruthy()
expect(view.queryByText('Try adjusting your search')).toBeNull()
})
it('AUM-04: a search with no results shows the adjust-search hint', async () => {
setUsersPages([{ users: [] }])
const view = renderUsers()
await flush()
fireEvent.changeText(view.getByPlaceholderText('Search by mobile number...'), '999')
await flush()
expect(view.getByText('No users found')).toBeTruthy()
expect(view.getByText('Try adjusting your search')).toBeTruthy()
})
it('AUM-05: a row shows mobile, name, registration, order count and last order', async () => {
setUsersPages([{ users: [USER_1] }])
const view = renderUsers()
await flush()
expect(view.getByText('9876543210')).toBeTruthy()
expect(view.getByText('Test User')).toBeTruthy()
expect(view.getByText(/^Registered: /)).toBeTruthy()
expect(view.getByText('3 orders')).toBeTruthy()
expect(view.getByText(/^Last: /)).toBeTruthy()
expect(view.getByText('Showing 1 users')).toBeTruthy()
})
it('AUM-06: a user without a name falls back to "Unnamed User"', async () => {
setUsersPages([{ users: [USER_NO_NAME] }])
const view = renderUsers()
await flush()
expect(view.getByText('Unnamed User')).toBeTruthy()
})
it('AUM-07: a user without a mobile falls back to "No Mobile"', async () => {
setUsersPages([{ users: [USER_NO_NAME] }])
const view = renderUsers()
await flush()
expect(view.getByText('No Mobile')).toBeTruthy()
})
it('AUM-08: a suspended user gets the Suspended badge', async () => {
setUsersPages([{ users: [{ ...USER_SUSPENDED, name: 'Blocked User' }] }])
const view = renderUsers()
await flush()
expect(view.getByText('Suspended')).toBeTruthy()
})
it('AUM-09: zero orders renders a gray "0 orders" label', async () => {
setUsersPages([{ users: [USER_SUSPENDED] }])
const view = renderUsers()
await flush()
const label = view.getByText('0 orders')
expect(StyleSheet.flatten(label.props.style).color).toBe((tw`text-gray-400` as any).color)
})
it('AUM-10: the search box feeds the query (untrimmed value, undefined when empty)', async () => {
setUsersPages([{ users: [USER_1] }])
const view = renderUsers()
await flush()
const input = view.getByPlaceholderText('Search by mobile number...')
fireEvent.changeText(input, ' 987 ')
await waitFor(() => {
expect(procedureQueryCalls('admin.user.getAllUsers').pop()).toEqual({
limit: 30,
search: ' 987 ',
direction: 'forward',
})
})
// Current page code uses `searchTerm || undefined` — no trim is applied.
fireEvent.changeText(input, '')
await flush()
// Clearing restores the cached empty-search query, whose request carried
// `search: undefined` (dropped from the wire payload by JSON.stringify).
const calls = procedureQueryCalls('admin.user.getAllUsers')
expect(calls[0]).toEqual({ limit: 30, search: undefined, direction: 'forward' })
expect(calls.every((call) => call.search !== '')).toBe(true)
})
it('AUM-11: end of list calls fetchNextPage and the appended page is rendered', async () => {
setUsersPages([
{ users: [USER_1, USER_SUSPENDED], nextCursor: 6 },
{ users: [USER_NO_NAME] },
])
const view = renderUsers()
await flush()
expect(view.getByText('9876543210')).toBeTruthy()
expect(view.queryByText('No Mobile')).toBeNull()
await loadNextPage(view)
expect(view.getByText('No Mobile')).toBeTruthy()
expect(procedureQueryCalls('admin.user.getAllUsers').pop()).toEqual({
limit: 30,
search: undefined,
cursor: 6,
direction: 'forward',
})
})
it('AUM-12: duplicate users across pages are deduped by id', async () => {
setUsersPages([
{ users: [USER_1, USER_SUSPENDED], nextCursor: 6 },
{ users: [USER_1] },
])
const view = renderUsers()
await flush()
expect(view.getByText('Showing 2 users')).toBeTruthy()
await loadNextPage(view)
expect(view.getAllByText('9876543210')).toHaveLength(1)
expect(view.getByText('Showing 2 users')).toBeTruthy()
})
it('AUM-13: pull-to-refresh runs the shared refresh (MyFlatList shadows the page handler)', async () => {
setUsersPages([{ users: [USER_1] }])
const view = renderUsers()
await flush()
// MyFlatList always injects its own RefreshControl (refreshAll) after
// `{...restProps}`, so the page's refetch handler never runs — current gap.
const clearSpy = jest.spyOn(view.queryClient, 'clear')
const callsBefore = procedureQueryCalls('admin.user.getAllUsers').length
const control = view.UNSAFE_getByType(RefreshControl)
await act(async () => {
control.props.onRefresh?.()
})
await flush()
expect(clearSpy).toHaveBeenCalled()
// The page's `handleRefresh` would have issued a new request; the shared
// refresh only clears the cache, so no additional query is sent.
expect(procedureQueryCalls('admin.user.getAllUsers')).toHaveLength(callsBefore)
})
it('AUM-14: the footer spinner shows while the next page is fetching', async () => {
setUsersPages([{ users: [USER_1], nextCursor: 5 }])
const view = renderUsers()
await flush()
expect(view.UNSAFE_queryAllByType(ActivityIndicator)).toHaveLength(0)
// Leave the second page request in flight.
setProcedure('admin.user.getAllUsers', { mode: 'pending' })
await loadNextPage(view)
expect(view.UNSAFE_getAllByType(ActivityIndicator).length).toBeGreaterThanOrEqual(1)
})
it('AUM-15: tapping a user opens their detail route', async () => {
setUsersPages([{ users: [USER_1] }])
const view = renderUsers()
await flush()
fireEvent.press(view.getByText('9876543210'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
})
it('AUM-16: a load-more failure keeps the list (no full-screen spinner after first load)', async () => {
setUsersPages([{ users: [USER_1], nextCursor: 5 }])
const view = renderUsers()
await flush()
setProcedure('admin.user.getAllUsers', { mode: 'error', error: new Error('load-more failed') })
await loadNextPage(view)
expect(view.queryByText('Loading users...')).toBeNull()
})
it('AUM-17: a new search starts a fresh query without a cursor', async () => {
setUsersPages([{ users: [USER_1], nextCursor: 5 }])
const view = renderUsers()
await flush()
fireEvent.changeText(view.getByPlaceholderText('Search by mobile number...'), '5')
await waitFor(() => {
const searches = procedureQueryCalls('admin.user.getAllUsers').filter(
(input) => input?.search === '5'
)
expect(searches).toHaveLength(1)
expect(searches[0]).toEqual({ limit: 30, search: '5', direction: 'forward' })
})
})
it('AUM-18: an empty search result has no Clear button (current UI)', async () => {
setUsersPages([{ users: [] }])
const view = renderUsers()
await flush()
fireEvent.changeText(view.getByPlaceholderText('Search by mobile number...'), 'zzz')
await flush()
expect(view.getByText('No users found')).toBeTruthy()
expect(view.getByText('Try adjusting your search')).toBeTruthy()
expect(view.queryByText('Clear')).toBeNull()
})
})