freshyo/apps/admin-ui/tests/components/user-incidents-view.test.tsx
2026-10-20 00:31:05 +05:30

277 lines
9.2 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Catalogue section 14.5 — User incidents (`tests/components/user-incidents-view.test.tsx`).
*
* The shared `USER_INCIDENTS` fixture is DB-shaped (`addedBy` is an object,
* `order` is nested). The component renders `addedBy` as a child, so this file
* feeds the procedure-shaped value the backend actually returns.
*/
import React from 'react'
import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native'
import dayjs from 'dayjs'
import { UserIncidentsView } from '@/components/UserIncidentsView'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset'
import { lastMutationInput, procedureMutationCalls, setProcedure } from '../mocks/trpc-client'
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.getUserIncidents') {
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 INCIDENT = {
id: 1,
userId: 5,
orderId: 11,
dateAdded: NOW,
adminComment: 'Late delivery',
addedBy: 'Admin One',
negativityScore: 2,
orderStatus: 'active',
}
function setIncidents(incidents: any[]) {
setProcedure('admin.user.getUserIncidents', { data: { incidents } })
}
function renderView(orderId: number | null = null) {
return renderWithProviders(<UserIncidentsView userId={5} orderId={orderId} />, { auth: 'in' })
}
async function openDialog(view: ReturnType<typeof renderView>) {
fireEvent.press(view.getByText('Add Incident'))
await flush()
}
async function pressSubmit(view: ReturnType<typeof renderView>) {
// [0] is the header button, [1] is the dialog's submit button.
fireEvent.press(view.getAllByText('Add Incident')[1])
await flush(2)
}
describe('User incidents view (AINC-01..09, AUIV-01..03)', () => {
let alertSpy: jest.SpyInstance
beforeEach(() => {
resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
setIncidents([])
})
afterEach(() => alertSpy?.mockRestore())
it('AINC-01: a pending query shows no spinner (current gap) and the empty copy', async () => {
setProcedure('admin.user.getUserIncidents', { mode: 'pending' })
const view = renderView()
await flush()
// The component never reads `isLoading`, so there is no spinner today.
expect(view.UNSAFE_queryAllByType(require('react-native').ActivityIndicator)).toHaveLength(0)
expect(view.getByText('No incidents recorded for this user')).toBeTruthy()
})
it('AINC-02: an empty list shows the empty copy', async () => {
const view = renderView()
await flush()
expect(view.getByText('No incidents recorded for this user')).toBeTruthy()
})
it('AINC-03: a row shows comment, date, addedBy, score and order', async () => {
setIncidents([INCIDENT])
const view = renderView()
await flush()
expect(view.getByText('Late delivery')).toBeTruthy()
expect(view.getByText(dayjs(NOW).format('MMM DD, YYYY • h:mm A'))).toBeTruthy()
expect(view.getByText('Added by Admin One')).toBeTruthy()
expect(view.getByText('Score: 2')).toBeTruthy()
expect(view.getByText('Order #11')).toBeTruthy()
// `orderStatus` is returned by the API but not rendered by the component.
expect(view.queryByText('active')).toBeNull()
})
it('AINC-04: Add Incident opens the dialog form', async () => {
const view = renderView()
await flush()
await openDialog(view)
expect(view.getByText('Add User Incident')).toBeTruthy()
expect(view.getByText('Admin Comment')).toBeTruthy()
expect(view.getByText('Negativity Score (Optional)')).toBeTruthy()
expect(view.getByPlaceholderText('Enter details about the incident...')).toBeTruthy()
expect(view.getByPlaceholderText('0')).toBeTruthy()
expect(view.getByText('Cancel')).toBeTruthy()
expect(view.getAllByText('Add Incident')).toHaveLength(2)
})
it('AINC-05: submitting nothing alerts and makes no API call', async () => {
const view = renderView()
await flush()
await openDialog(view)
await pressSubmit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Please enter a comment or negativity score')
expect(procedureMutationCalls('admin.user.addUserIncident')).toHaveLength(0)
})
it('AINC-06: submitting sends the mutation, alerts, refetches and resets the form', async () => {
const view = renderView()
await flush()
await openDialog(view)
fireEvent.changeText(
view.getByPlaceholderText('Enter details about the incident...'),
'Rude to staff'
)
await pressSubmit(view)
expect(lastMutationInput('admin.user.addUserIncident')).toEqual({
userId: 5,
orderId: undefined,
adminComment: 'Rude to staff',
negativityScore: undefined,
})
expect(alertSpy).toHaveBeenCalledWith('Success', 'Incident added successfully')
expect(trpcMock.__refetch).toHaveBeenCalled()
expect(view.queryByText('Add User Incident')).toBeNull()
})
it('AINC-07: a failed mutation alerts the error', async () => {
setProcedure('admin.user.addUserIncident', { mode: 'error', error: new Error('boom') })
const view = renderView()
await flush()
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
await pressSubmit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
})
it('AINC-08: an order-scoped incident sends orderId + parsed score, omitting empty fields', async () => {
const view = renderView(11)
await flush()
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
fireEvent.changeText(view.getByPlaceholderText('0'), '3')
await pressSubmit(view)
expect(lastMutationInput('admin.user.addUserIncident')).toEqual({
userId: 5,
orderId: 11,
adminComment: 'Rude',
negativityScore: 3,
})
})
it('AINC-09: a pending submit shows "Adding..." and disables a second submit', async () => {
setProcedure('admin.user.addUserIncident', { mode: 'pending' })
const view = renderView()
await flush()
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
fireEvent.press(view.getAllByText('Add Incident')[1])
await flush(2)
expect(view.getByText('Adding...')).toBeTruthy()
fireEvent.press(view.getByText('Adding...'))
await act(async () => {
await flush()
})
expect(procedureMutationCalls('admin.user.addUserIncident')).toHaveLength(1)
})
/* ---------------------------------------------------------------------- */
/* Catalogue §17.1 — UserIncidentsView aliases */
/* ---------------------------------------------------------------------- */
it('AUIV-01: renders the empty state and then a populated list', async () => {
setIncidents([])
const empty = renderView()
await flush()
expect(empty.getByText('No incidents recorded for this user')).toBeTruthy()
empty.unmount()
setIncidents([INCIDENT])
const view = renderView()
await flush()
expect(view.getByText('Late delivery')).toBeTruthy()
expect(view.getByText('Added by Admin One')).toBeTruthy()
expect(view.getByText('Score: 2')).toBeTruthy()
})
it('AUIV-02: adding an incident calls the API and refetches', async () => {
const view = renderView()
await flush()
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
await pressSubmit(view)
expect(lastMutationInput('admin.user.addUserIncident')).toEqual({
userId: 5,
orderId: undefined,
adminComment: 'Rude',
negativityScore: undefined,
})
expect(trpcMock.__refetch).toHaveBeenCalled()
})
it('AUIV-03: a failed add alerts the error', async () => {
setProcedure('admin.user.addUserIncident', { mode: 'error', error: new Error('boom') })
const view = renderView()
await flush()
await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
await pressSubmit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
})
})