This commit is contained in:
shafi54 2026-10-20 11:19:25 +05:30
parent f9ce91681d
commit 2db4375a5f
88 changed files with 3997 additions and 3133 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

View file

@ -151,3 +151,46 @@ directly.
`COUPON_INVALIDATED`, `COUPON_RESERVED`, `COUPONS`, `TAG_1`, `TAG_2`, `TAGS`, `COUPON_INVALIDATED`, `COUPON_RESERVED`, `COUPONS`, `TAG_1`, `TAG_2`, `TAGS`,
`GROUP_1`, `GROUPS`, `BANNER_1`, `BANNERS`, `SNIPPET_1`, `SNIPPETS`, `GROUP_1`, `GROUPS`, `BANNER_1`, `BANNERS`, `SNIPPET_1`, `SNIPPETS`,
`SNIPPET_ORDERS`, `COMPLAINT_1`, `COMPLAINT_2`, `COMPLAINTS`, `TEST_JWT`. `SNIPPET_ORDERS`, `COMPLAINT_1`, `COMPLAINT_2`, `COMPLAINTS`, `TEST_JWT`.
---
## Real tRPC client, mocked network (current harness)
The app's **real** `@/src/trpc-client` and **real React Query** run in tests. Only
the network response is faked:
```
real hook → real httpBatchLink → global fetch (tRPC network mock) → procedure registry
```
- `tests/mocks/trpc-client.ts` no longer replaces the client module. It exports the
procedure registry (`setProcedure`, defaults, call recording) and
`installTrpcNetworkMock()`, which `tests/setup.ts` installs on `global.fetch`.
- The mock parses the client's batch request
(`GET /api/trpc/a.b,c.d?batch=1&input=…` / `POST … body {"0":…}`) and answers
with the tRPC batch envelope. `mode: 'pending'` keeps the hook loading;
`mode: 'error'` returns a tRPC error entry.
- `renderWithProviders` wraps with `QueryClientProvider` **and** the real
`trpc.Provider`.
- `lastProcedureInput` / `procedureMutationCalls` are filled from the real
requests. `useUtils().x.invalidate()` is real; the test QueryClient records the
query keys so `procedureInvalidations(path)` still works.
### Assertions are asynchronous
Queries resolve after a tick and mutations settle asynchronously. Prefer:
```tsx
const view = renderWithProviders(<Page />, { auth: 'in' })
expect(await view.findByText('Chicken Breast')).toBeTruthy()
fireEvent.press(view.getByTestId('save'))
await waitFor(() => expect(lastProcedureInput('user.order.updateUserNotes')).toEqual({ … }))
```
`renderAndFlush(ui)` renders and drains the first round of queries when a test
does several synchronous lookups. Check `isLoading` / `Processing…` **before**
awaiting, and never assume a mutation has completed on the next line.
`forceExit` is enabled in `jest.config.js` because a `mode: 'pending'` fixture
leaves the client's request timer open.

View file

@ -125,8 +125,8 @@ describe('Drawer layout (ADRAW-01..19)', () => {
it('ADRAW-03: renders the staff name and region from the me query', async () => { it('ADRAW-03: renders the staff name and region from the me query', async () => {
const view = await renderDrawer() const view = await renderDrawer()
expect(await view.findByText('Mahabubnagar')).toBeTruthy()
expect(view.getByText('Admin One')).toBeTruthy() expect(view.getByText('Admin One')).toBeTruthy()
expect(view.getByText('Mahabubnagar')).toBeTruthy()
}) })
it('ADRAW-04: falls back to the stored staff when me is unavailable', async () => { it('ADRAW-04: falls back to the stored staff when me is unavailable', async () => {
@ -141,15 +141,15 @@ describe('Drawer layout (ADRAW-01..19)', () => {
setProcedure('admin.staffUser.me', { data: { name: 'Unassigned', regionId: 0 } }) setProcedure('admin.staffUser.me', { data: { name: 'Unassigned', regionId: 0 } })
const view = await renderDrawer() const view = await renderDrawer()
expect(await view.findByText('No region')).toBeTruthy()
expect(view.getByText('Unassigned')).toBeTruthy() expect(view.getByText('Unassigned')).toBeTruthy()
expect(view.getByText('No region')).toBeTruthy()
}) })
it('ADRAW-06: a region without a name renders "Region #<id>"', async () => { it('ADRAW-06: a region without a name renders "Region #<id>"', async () => {
setProcedure('admin.staffUser.me', { data: { name: 'Admin Two', regionId: 2 } }) setProcedure('admin.staffUser.me', { data: { name: 'Admin Two', regionId: 2 } })
const view = await renderDrawer() const view = await renderDrawer()
expect(view.getByText('Region #2')).toBeTruthy() expect(await view.findByText('Region #2')).toBeTruthy()
}) })
it('ADRAW-07: Dashboard dismisses to the dashboard route', async () => { it('ADRAW-07: Dashboard dismisses to the dashboard route', async () => {

View file

@ -55,17 +55,16 @@ function openUsers(view: View) {
} }
/** /**
* The mock resolves the user query synchronously, so the form's "reset on open" * Re-seed the users response and make the cached query stale before the dialog
* effect clears the list before the data effect can see a change. Re-seeding * opens, so the real React Query refetches when the query is re-enabled.
* with a fresh payload after the dialog opens reproduces the real fetch timing.
*/ */
async function openUsersWith( async function openUsersWith(
view: View, view: View,
users: { id: number; name: string; mobile: string }[] users: { id: number; name: string; mobile: string }[]
) { ) {
openUsers(view)
await flush(1)
setProcedure('admin.coupon.getUsersMiniInfo', { data: { users: [...users], count: users.length } }) setProcedure('admin.coupon.getUsersMiniInfo', { data: { users: [...users], count: users.length } })
await view.queryClient.invalidateQueries()
openUsers(view)
await flush(2) await flush(2)
} }
@ -351,6 +350,7 @@ describe('CouponForm (ACOUPF-01..24)', () => {
view.getByText('No products selected - the coupon applies to the whole cart.') view.getByText('No products selected - the coupon applies to the whole cart.')
).toBeTruthy() ).toBeTruthy()
await flush()
fireEvent.press(view.getByTestId('coupon-products-selector')) fireEvent.press(view.getByTestId('coupon-products-selector'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-11')) fireEvent.press(view.getByTestId('coupon-products-selector-option-11'))
fireEvent.press(view.getByTestId('coupon-products-selector-done')) fireEvent.press(view.getByTestId('coupon-products-selector-done'))
@ -359,10 +359,11 @@ describe('CouponForm (ACOUPF-01..24)', () => {
expect(onSubmit.mock.calls[0][0].skuIds).toEqual([11]) expect(onSubmit.mock.calls[0][0].skuIds).toEqual([11])
}) })
it('ACOUPF-19: the product count copy reflects the selection', () => { it('ACOUPF-19: the product count copy reflects the selection', async () => {
const { view } = renderForm() const { view } = renderForm()
fireEvent.changeText(codeInput(view), 'SAVE10') fireEvent.changeText(codeInput(view), 'SAVE10')
await flush()
fireEvent.press(view.getByTestId('coupon-products-selector')) fireEvent.press(view.getByTestId('coupon-products-selector'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-11')) fireEvent.press(view.getByTestId('coupon-products-selector-option-11'))
fireEvent.press(view.getByTestId('coupon-products-selector-option-13')) fireEvent.press(view.getByTestId('coupon-products-selector-option-13'))

View file

@ -233,6 +233,7 @@ describe('ProductForm (APFORM-01..22)', () => {
it('APFORM-14: a duplicate combo SKU is rejected and not set', async () => { it('APFORM-14: a duplicate combo SKU is rejected and not set', async () => {
const { view } = renderForm() const { view } = renderForm()
await flush()
fireEvent.press(view.getByTestId('product-type-dropdown')) fireEvent.press(view.getByTestId('product-type-dropdown'))
fireEvent.press(view.getByTestId('product-type-dropdown-option-combo')) fireEvent.press(view.getByTestId('product-type-dropdown-option-combo'))
@ -266,8 +267,9 @@ describe('ProductForm (APFORM-01..22)', () => {
expect(view.queryByTestId('variant-0-combo-0-dropdown')).toBeNull() expect(view.queryByTestId('variant-0-combo-0-dropdown')).toBeNull()
}) })
it('APFORM-16: the store dropdown labels regional and global stores', () => { it('APFORM-16: the store dropdown labels regional and global stores', async () => {
const { view } = renderForm() const { view } = renderForm()
await flush()
fireEvent.press(view.getByTestId('product-store-dropdown')) fireEvent.press(view.getByTestId('product-store-dropdown'))
@ -275,8 +277,9 @@ describe('ProductForm (APFORM-01..22)', () => {
expect(view.getByText('Freshyo Central (global)')).toBeTruthy() expect(view.getByText('Freshyo Central (global)')).toBeTruthy()
}) })
it('APFORM-17: a create form with no store prefers the regional store', () => { it('APFORM-17: a create form with no store prefers the regional store', async () => {
const { view } = renderForm({ storeId: 0 }) const { view } = renderForm({ storeId: 0 })
await flush()
expect(view.getByText('The Freshyo Meat House')).toBeTruthy() expect(view.getByText('The Freshyo Meat House')).toBeTruthy()
expect(view.queryByText('Select store')).toBeNull() expect(view.queryByText('Select store')).toBeNull()

View file

@ -87,8 +87,9 @@ describe('ProductGroupForm (AGRPF-01..08)', () => {
expect(onSuccess).toHaveBeenCalled() expect(onSuccess).toHaveBeenCalled()
}) })
it('AGRPF-04: renders the edit heading and prefilled values', () => { it('AGRPF-04: renders the edit heading and prefilled values', async () => {
const { view } = renderForm(GROUP_1 as ProductGroup) const { view } = renderForm(GROUP_1 as ProductGroup)
await flush()
expect(view.getByText('Edit Product Group')).toBeTruthy() expect(view.getByText('Edit Product Group')).toBeTruthy()
expect(nameInput(view).props.value).toBe('Breakfast') expect(nameInput(view).props.value).toBe('Breakfast')

View file

@ -87,6 +87,7 @@ describe('SlotForm (ASLOTF-01..10)', () => {
it('ASLOTF-04: selecting products sends the SKU ids', async () => { it('ASLOTF-04: selecting products sends the SKU ids', async () => {
const view = renderSlotForm() const view = renderSlotForm()
await flush()
selectSku(view, 'slot-products-selector', 13) selectSku(view, 'slot-products-selector', 13)
const { delivery, freeze } = setDates(view) const { delivery, freeze } = setDates(view)
@ -104,6 +105,7 @@ describe('SlotForm (ASLOTF-01..10)', () => {
it('ASLOTF-05: adding a vendor snippet includes name, SKUs and no expiry', async () => { it('ASLOTF-05: adding a vendor snippet includes name, SKUs and no expiry', async () => {
const view = renderSlotForm() const view = renderSlotForm()
await flush()
selectSku(view, 'slot-products-selector', 13) selectSku(view, 'slot-products-selector', 13)
fireEvent.press(view.getByText('Add Vendor Snippet')) fireEvent.press(view.getByText('Add Vendor Snippet'))
@ -146,6 +148,7 @@ describe('SlotForm (ASLOTF-01..10)', () => {
it('ASLOTF-08: group selection is sent as group ids', async () => { it('ASLOTF-08: group selection is sent as group ids', async () => {
const view = renderSlotForm() const view = renderSlotForm()
await flush()
fireEvent.press(view.getByTestId('product-groups-dropdown')) fireEvent.press(view.getByTestId('product-groups-dropdown'))
fireEvent.press(view.getByTestId('product-groups-dropdown-option-1')) fireEvent.press(view.getByTestId('product-groups-dropdown-option-1'))
@ -269,8 +272,9 @@ describe('VendorSnippetForm (AVSF-01..08)', () => {
expect(view.getAllByText(validTill.toLocaleDateString()).length).toBeGreaterThanOrEqual(1) expect(view.getAllByText(validTill.toLocaleDateString()).length).toBeGreaterThanOrEqual(1)
}) })
it('AVSF-06: the product selector updates the selection', () => { it('AVSF-06: the product selector updates the selection', async () => {
const view = renderSnippetForm() const view = renderSnippetForm()
await flush()
selectSku(view, 'snippet-form-products-selector', 11) selectSku(view, 'snippet-form-products-selector', 11)
@ -279,6 +283,7 @@ describe('VendorSnippetForm (AVSF-01..08)', () => {
it('AVSF-07: submit sends the complete snippet payload', async () => { it('AVSF-07: submit sends the complete snippet payload', async () => {
const view = renderSnippetForm() const view = renderSnippetForm()
await flush()
fireEvent.changeText(view.getByTestId('snippet-code-input'), 'TEST_1') fireEvent.changeText(view.getByTestId('snippet-code-input'), 'TEST_1')
fireEvent.press(view.getByText('Is Permanent?')) fireEvent.press(view.getByText('Is Permanent?'))

View file

@ -5,13 +5,13 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
import StoreForm, { StoreFormData } from '@/components/StoreForm' import StoreForm, { StoreFormData } from '@/components/StoreForm'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client' import { setProcedure, setRawFetchHandler } from '../mocks/trpc-client'
import { STORE_1 } from '../fixtures' import { STORE_1 } from '../fixtures'
jest.mock('common-ui/src/components/ImageUploader', () => { jest.mock('common-ui/src/components/ImageUploader', () => {
@ -82,11 +82,12 @@ describe('StoreForm (ASTOREF-01..11)', () => {
resetAllMocks() resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({ canceled: true, assets: null }) ;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({ canceled: true, assets: null })
;(global as any).fetch = jest.fn(async (url: string) => { // Non-tRPC requests (file:// reads and presigned PUTs) go through the raw handler.
setRawFetchHandler(async (url: string) => {
if (String(url).startsWith('file:')) { if (String(url).startsWith('file:')) {
return { ok: true, blob: async () => ({ size: 1 }) } return { ok: true, blob: async () => ({ size: 1 }) } as any
} }
return { ok: true, status: 200, text: async () => '' } return { ok: true, status: 200, text: async () => '' } as any
}) })
}) })
@ -142,9 +143,9 @@ describe('StoreForm (ASTOREF-01..11)', () => {
await flush() await flush()
fireEvent.press(view.getByTestId('store-submit-button')) fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2) await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ imageUrl: PRICE_URL })) expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ imageUrl: PRICE_URL }))
})
expect(global.fetch).toHaveBeenCalledWith(PRICE_URL, expect.objectContaining({ method: 'PUT' })) expect(global.fetch).toHaveBeenCalledWith(PRICE_URL, expect.objectContaining({ method: 'PUT' }))
}) })
@ -171,12 +172,13 @@ describe('StoreForm (ASTOREF-01..11)', () => {
expect(view.queryByText('Name is required')).toBeNull() expect(view.queryByText('Name is required')).toBeNull()
}) })
it('ASTOREF-08: onSubmit receives the values, the SKU selection and imageUrl', () => { it('ASTOREF-08: onSubmit receives the values, the SKU selection and imageUrl', async () => {
const { view, onSubmit } = renderForm({ const { view, onSubmit } = renderForm({
mode: 'edit', mode: 'edit',
storeId: 1, storeId: 1,
initialValues: { ...initialValues, name: STORE_1.name }, initialValues: { ...initialValues, name: STORE_1.name },
}) })
await flush(2)
fireEvent.changeText(view.getByTestId('store-name-input'), 'My Store') fireEvent.changeText(view.getByTestId('store-name-input'), 'My Store')
fireEvent.changeText(view.getByTestId('store-description-input'), 'A description') fireEvent.changeText(view.getByTestId('store-description-input'), 'A description')

View file

@ -116,6 +116,8 @@ describe('TagForm (ATAGF-01..08)', () => {
it('ATAGF-06: product selection submits product ids', async () => { it('ATAGF-06: product selection submits product ids', async () => {
const { view, onSubmit } = renderForm() const { view, onSubmit } = renderForm()
// SKU options arrive from a real query; wait for them before selecting.
await flush()
const dropdowns = view.UNSAFE_getAllByType(BottomDropdown) const dropdowns = view.UNSAFE_getAllByType(BottomDropdown)
const productsDropdown = dropdowns[dropdowns.length - 1] const productsDropdown = dropdowns[dropdowns.length - 1]

View file

@ -8,48 +8,18 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { UserIncidentsView } from '@/components/UserIncidentsView' import { UserIncidentsView } from '@/components/UserIncidentsView'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { lastMutationInput, procedureMutationCalls, setProcedure } from '../mocks/trpc-client' import {
lastMutationInput,
jest.mock('../mocks/trpc-client', () => { procedureMutationCalls,
const actual = jest.requireActual('../mocks/trpc-client') procedureQueryCalls,
const refetch = jest.fn(async () => ({ data: undefined })) setProcedure,
const nodeFor = (path: string) => } from '../mocks/trpc-client'
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 NOW = new Date().toISOString()
@ -162,16 +132,23 @@ describe('User incidents view (AINC-01..09, AUIV-01..03)', () => {
view.getByPlaceholderText('Enter details about the incident...'), view.getByPlaceholderText('Enter details about the incident...'),
'Rude to staff' 'Rude to staff'
) )
const queriesBefore = procedureQueryCalls('admin.user.getUserIncidents').length
await pressSubmit(view) await pressSubmit(view)
await waitFor(() => {
expect(lastMutationInput('admin.user.addUserIncident')).toEqual({ expect(lastMutationInput('admin.user.addUserIncident')).toEqual({
userId: 5, userId: 5,
orderId: undefined, orderId: undefined,
adminComment: 'Rude to staff', adminComment: 'Rude to staff',
negativityScore: undefined, negativityScore: undefined,
}) })
})
expect(alertSpy).toHaveBeenCalledWith('Success', 'Incident added successfully') expect(alertSpy).toHaveBeenCalledWith('Success', 'Incident added successfully')
expect(trpcMock.__refetch).toHaveBeenCalled() await waitFor(() => {
expect(procedureQueryCalls('admin.user.getUserIncidents').length).toBeGreaterThan(
queriesBefore
)
})
expect(view.queryByText('Add User Incident')).toBeNull() expect(view.queryByText('Add User Incident')).toBeNull()
}) })
@ -251,15 +228,22 @@ describe('User incidents view (AINC-01..09, AUIV-01..03)', () => {
await openDialog(view) await openDialog(view)
fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude') fireEvent.changeText(view.getByPlaceholderText('Enter details about the incident...'), 'Rude')
const queriesBefore = procedureQueryCalls('admin.user.getUserIncidents').length
await pressSubmit(view) await pressSubmit(view)
await waitFor(() => {
expect(lastMutationInput('admin.user.addUserIncident')).toEqual({ expect(lastMutationInput('admin.user.addUserIncident')).toEqual({
userId: 5, userId: 5,
orderId: undefined, orderId: undefined,
adminComment: 'Rude', adminComment: 'Rude',
negativityScore: undefined, negativityScore: undefined,
}) })
expect(trpcMock.__refetch).toHaveBeenCalled() })
await waitFor(() => {
expect(procedureQueryCalls('admin.user.getUserIncidents').length).toBeGreaterThan(
queriesBefore
)
})
}) })
it('AUIV-03: a failed add alerts the error', async () => { it('AUIV-03: a failed add alerts the error', async () => {

View file

@ -5,7 +5,7 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent, render } from '@testing-library/react-native' import { fireEvent } from '@testing-library/react-native'
jest.mock('@/components/context/staff-auth-context', () => jest.mock('@/components/context/staff-auth-context', () =>
require('../mocks/staff-auth-context') require('../mocks/staff-auth-context')
@ -14,17 +14,18 @@ jest.mock('@/components/context/staff-auth-context', () =>
import VendorSnippetForm from '@/components/VendorSnippetForm' import VendorSnippetForm from '@/components/VendorSnippetForm'
import { __setStaffState } from '../mocks/staff-auth-context' import { __setStaffState } from '../mocks/staff-auth-context'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { flush } from '../helpers/test-utils' import { flush, renderWithProviders } from '../helpers/test-utils'
import { lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client' import { lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
import { SLOT_1, SNIPPET_1, STAFF } from '../fixtures' import { SLOT_1, SNIPPET_1, STAFF } from '../fixtures'
function renderForm(props: Partial<React.ComponentProps<typeof VendorSnippetForm>> = {}) { function renderForm(props: Partial<React.ComponentProps<typeof VendorSnippetForm>> = {}) {
return render( return renderWithProviders(
<VendorSnippetForm onClose={jest.fn()} onSuccess={jest.fn()} {...props} /> <VendorSnippetForm onClose={jest.fn()} onSuccess={jest.fn()} {...props} />,
{ auth: 'in' }
) )
} }
async function selectProduct(view: ReturnType<typeof render>, label: string) { async function selectProduct(view: ReturnType<typeof renderForm>, label: string) {
fireEvent.press(view.getByText('Select products')) fireEvent.press(view.getByText('Select products'))
fireEvent.press(view.getByText(label)) fireEvent.press(view.getByText(label))
fireEvent.press(view.getByText('Done')) fireEvent.press(view.getByText('Done'))
@ -94,6 +95,7 @@ describe('VendorSnippetForm (AVFORM-01..08)', () => {
it('AVFORM-05: the product selector stores the selected SKU ids', async () => { it('AVFORM-05: the product selector stores the selected SKU ids', async () => {
const view = renderForm() const view = renderForm()
await flush()
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'CODE123') fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'CODE123')
fireEvent.press(view.getByText('Is Permanent?')) fireEvent.press(view.getByText('Is Permanent?'))
@ -116,6 +118,7 @@ describe('VendorSnippetForm (AVFORM-01..08)', () => {
const onClose = jest.fn() const onClose = jest.fn()
const onSuccess = jest.fn() const onSuccess = jest.fn()
const view = renderForm({ onClose, onSuccess }) const view = renderForm({ onClose, onSuccess })
await flush()
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'MYCODE') fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'MYCODE')
fireEvent.press(view.getByText('Choose a delivery slot')) fireEvent.press(view.getByText('Choose a delivery slot'))
@ -140,6 +143,7 @@ describe('VendorSnippetForm (AVFORM-01..08)', () => {
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const onSuccess = jest.fn() const onSuccess = jest.fn()
const view = renderForm({ snippet: SNIPPET_1 as any, onSuccess }) const view = renderForm({ snippet: SNIPPET_1 as any, onSuccess })
await flush()
expect(view.getByText('Edit Vendor Snippet')).toBeTruthy() expect(view.getByText('Edit Vendor Snippet')).toBeTruthy()
expect(view.getByDisplayValue('ABC123')).toBeTruthy() expect(view.getByDisplayValue('ABC123')).toBeTruthy()

View file

@ -3,12 +3,14 @@ import * as React from 'react'
import { render as rtlRender, RenderResult } from '@testing-library/react-native' import { render as rtlRender, RenderResult } from '@testing-library/react-native'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RefreshProvider } from 'common-ui' import { RefreshProvider } from 'common-ui'
import { trpc, trpcClient } from '@/src/trpc-client'
import { recordQueryInvalidation } from '../mocks/trpc-client'
import { StaffAuthProvider } from '@/components/context/staff-auth-context' import { StaffAuthProvider } from '@/components/context/staff-auth-context'
import { __set as setSecureItem, __delete as deleteSecureItem } from '../mocks/secure-store-mock' import { __set as setSecureItem, __delete as deleteSecureItem } from '../mocks/secure-store-mock'
import { STAFF, TEST_JWT } from '../fixtures' import { STAFF, TEST_JWT } from '../fixtures'
export function createTestQueryClient(): QueryClient { export function createTestQueryClient(): QueryClient {
return new QueryClient({ const queryClient = new QueryClient({
defaultOptions: { defaultOptions: {
queries: { queries: {
retry: false, retry: false,
@ -19,6 +21,14 @@ export function createTestQueryClient(): QueryClient {
mutations: { retry: false }, mutations: { retry: false },
}, },
}) })
const originalInvalidate = queryClient.invalidateQueries.bind(queryClient)
;(queryClient as any).invalidateQueries = ((filters?: any, options?: any) => {
recordQueryInvalidation(filters)
return originalInvalidate(filters, options)
}) as any
return queryClient
} }
type AuthMode = 'in' | 'out' | false type AuthMode = 'in' | 'out' | false
@ -67,6 +77,7 @@ export function renderWithProviders(
if (withRefresh) { if (withRefresh) {
tree = React.createElement(RefreshProvider, { queryClient, children: tree } as any) tree = React.createElement(RefreshProvider, { queryClient, children: tree } as any)
} }
tree = React.createElement(trpc.Provider, { client: trpcClient, queryClient, children: tree })
tree = React.createElement(QueryClientProvider, { client: queryClient }, tree) tree = React.createElement(QueryClientProvider, { client: queryClient }, tree)
return tree return tree
} }
@ -86,7 +97,7 @@ export async function renderAndFlush(
} }
/** Await a macrotask so promise chains and effects settle. */ /** Await a macrotask so promise chains and effects settle. */
export async function flush(times = 1) { export async function flush(times = 2) {
const { act } = require('@testing-library/react-native') const { act } = require('@testing-library/react-native')
for (let index = 0; index < times; index += 1) { for (let index = 0; index < times; index += 1) {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop

View file

@ -51,10 +51,6 @@ module.exports = {
], ],
moduleNameMapper: { moduleNameMapper: {
// Manual mocks first (order matters: moduleNameMapper is first-match-wins). // Manual mocks first (order matters: moduleNameMapper is first-match-wins).
'^(.*/)?src/trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^\\./trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^\\.\\./trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^@/src/trpc-client$': '<rootDir>/mocks/trpc-client.ts',
// Native / platform modules -> shared shims (every copy of a package, root // Native / platform modules -> shared shims (every copy of a package, root
// or packages/ui/node_modules, resolves to the same mock). // or packages/ui/node_modules, resolves to the same mock).
'^react-native-reanimated$': path.join(repoRoot, 'node_modules/react-native-reanimated/mock.js'), '^react-native-reanimated$': path.join(repoRoot, 'node_modules/react-native-reanimated/mock.js'),
@ -103,4 +99,6 @@ module.exports = {
testTimeout: 20000, testTimeout: 20000,
verbose: false, verbose: false,
maxWorkers: '50%', maxWorkers: '50%',
// Real React Query + tRPC client can leave pending timers; force exit.
forceExit: true,
} }

View file

@ -5,15 +5,25 @@
* *
* The hook is exercised through a probe component so React state * The hook is exercised through a probe component so React state
* (`isUploading`) can be observed while the upload is in flight. * (`isUploading`) can be observed while the upload is in flight.
*
* The real tRPC client + React Query run, so the probe needs the same providers
* as a page. Presigned PUTs go to a non-tRPC URL and are answered by
* `setRawFetchHandler` (never by replacing `global.fetch`, which would take the
* harness' tRPC network mock with it).
*/ */
import React from 'react' import React from 'react'
import { Text } from 'react-native' import { Text } from 'react-native'
import { act, render } from '@testing-library/react-native' import { act } from '@testing-library/react-native'
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore' import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { lastMutationInput, procedureMutationCalls, setProcedure } from '../mocks/trpc-client' import {
import { flush } from '../helpers/test-utils' lastMutationInput,
procedureMutationCalls,
setProcedure,
setRawFetchHandler,
} from '../mocks/trpc-client'
import { renderWithProviders, flush } from '../helpers/test-utils'
import { UPLOAD_URLS_RESPONSE } from '../fixtures' import { UPLOAD_URLS_RESPONSE } from '../fixtures'
type HookApi = ReturnType<typeof useUploadToObjectStorage> type HookApi = ReturnType<typeof useUploadToObjectStorage>
@ -35,8 +45,7 @@ function Probe() {
} }
function renderProbe() { function renderProbe() {
const view = render(<Probe />) return renderWithProviders(<Probe />, { auth: false })
return view
} }
const blob = {} as any const blob = {} as any
@ -46,12 +55,24 @@ const OK_RESPONSE = {
text: async () => '', text: async () => '',
json: async () => ({}), json: async () => ({}),
} }
const ERROR_RESPONSE = {
ok: false,
status: 500,
text: async () => '<Error><Code>InternalError</Code></Error>',
json: async () => ({}),
}
/** Records the presigned PUTs the hook makes (non-tRPC requests). */
function stubPut(response: any = OK_RESPONSE) {
const put = jest.fn(async (_url: string, _init?: any) => ({ ...response }))
setRawFetchHandler(put as any)
return put
}
describe('useUploadToObjectStorage (AUPL-01..06)', () => { describe('useUploadToObjectStorage (AUPL-01..06)', () => {
beforeEach(() => { beforeEach(() => {
resetAllMocks() resetAllMocks()
hook = null hook = null
;(global as any).fetch = jest.fn(async () => ({ ...OK_RESPONSE }))
}) })
afterEach(() => { afterEach(() => {
@ -59,6 +80,7 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
}) })
it('AUPL-01: uploads a single image via the presigned PUT and returns key/url', async () => { it('AUPL-01: uploads a single image via the presigned PUT and returns key/url', async () => {
const put = stubPut()
const view = renderProbe() const view = renderProbe()
let result: any let result: any
await act(async () => { await act(async () => {
@ -70,8 +92,8 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
mimeTypes: ['image/jpeg'], mimeTypes: ['image/jpeg'],
}) })
expect((global as any).fetch).toHaveBeenCalledTimes(1) expect(put).toHaveBeenCalledTimes(1)
const [url, options] = ((global as any).fetch as jest.Mock).mock.calls[0] const [url, options] = put.mock.calls[0]
expect(url).toBe(UPLOAD_URLS_RESPONSE.uploadUrls[0]) expect(url).toBe(UPLOAD_URLS_RESPONSE.uploadUrls[0])
expect(options).toMatchObject({ expect(options).toMatchObject({
method: 'PUT', method: 'PUT',
@ -92,6 +114,7 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
'https://upload.test/meatfarmer/review-images/b.png', 'https://upload.test/meatfarmer/review-images/b.png',
] ]
setProcedure('common.generateUploadUrls', { data: { uploadUrls: urls } }) setProcedure('common.generateUploadUrls', { data: { uploadUrls: urls } })
const put = stubPut()
const view = renderProbe() const view = renderProbe()
let result: any let result: any
@ -109,8 +132,8 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
contextString: 'review', contextString: 'review',
mimeTypes: ['image/jpeg', 'image/png'], mimeTypes: ['image/jpeg', 'image/png'],
}) })
expect((global as any).fetch).toHaveBeenCalledTimes(2) expect(put).toHaveBeenCalledTimes(2)
expect(((global as any).fetch as jest.Mock).mock.calls.map((call: any[]) => call[0])).toEqual(urls) expect(put.mock.calls.map((call: any[]) => call[0])).toEqual(urls)
expect(result).toEqual({ expect(result).toEqual({
keys: ['review-images/a.jpg', 'review-images/b.png'], keys: ['review-images/a.jpg', 'review-images/b.png'],
presignedUrls: urls, presignedUrls: urls,
@ -119,6 +142,7 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
}) })
it('AUPL-03: an empty image list makes no URL or PUT request', async () => { it('AUPL-03: an empty image list makes no URL or PUT request', async () => {
const put = stubPut()
const view = renderProbe() const view = renderProbe()
let result: any let result: any
@ -128,11 +152,12 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
expect(result).toEqual({ keys: [], presignedUrls: [] }) expect(result).toEqual({ keys: [], presignedUrls: [] })
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(0) expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(0)
expect((global as any).fetch).not.toHaveBeenCalled() expect(put).not.toHaveBeenCalled()
expect(view.getByTestId('uploading').props.children).toBe('idle') expect(view.getByTestId('uploading').props.children).toBe('idle')
}) })
it('AUPL-04: rejects when the URL count does not match the image count', async () => { it('AUPL-04: rejects when the URL count does not match the image count', async () => {
const put = stubPut()
const view = renderProbe() const view = renderProbe()
let error: any let error: any
@ -152,7 +177,7 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
expect(error).toBeInstanceOf(Error) expect(error).toBeInstanceOf(Error)
expect(error.message).toBe('Expected 2 URLs, got 1') expect(error.message).toBe('Expected 2 URLs, got 1')
expect((global as any).fetch).not.toHaveBeenCalled() expect(put).not.toHaveBeenCalled()
await flush() await flush()
expect(view.getByTestId('error').props.children).toBe('Expected 2 URLs, got 1') expect(view.getByTestId('error').props.children).toBe('Expected 2 URLs, got 1')
expect(view.getByTestId('uploading').props.children).toBe('idle') expect(view.getByTestId('uploading').props.children).toBe('idle')
@ -160,12 +185,7 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
it('AUPL-05: rejects when the presigned PUT fails', async () => { it('AUPL-05: rejects when the presigned PUT fails', async () => {
jest.spyOn(console, 'error').mockImplementation(() => undefined) jest.spyOn(console, 'error').mockImplementation(() => undefined)
;(global as any).fetch = jest.fn(async () => ({ const put = stubPut(ERROR_RESPONSE)
ok: false,
status: 500,
text: async () => '<Error><Code>InternalError</Code></Error>',
json: async () => ({}),
}))
const view = renderProbe() const view = renderProbe()
let error: any let error: any
@ -179,6 +199,7 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
expect(error).toBeInstanceOf(Error) expect(error).toBeInstanceOf(Error)
expect(error.message).toBe('Upload 1 failed with status 500') expect(error.message).toBe('Upload 1 failed with status 500')
expect(put).toHaveBeenCalledTimes(1)
await flush() await flush()
expect(view.getByTestId('error').props.children).toBe('Upload 1 failed with status 500') expect(view.getByTestId('error').props.children).toBe('Upload 1 failed with status 500')
expect(view.getByTestId('uploading').props.children).toBe('idle') expect(view.getByTestId('uploading').props.children).toBe('idle')
@ -189,7 +210,7 @@ describe('useUploadToObjectStorage (AUPL-01..06)', () => {
const pendingPut = new Promise((resolve) => { const pendingPut = new Promise((resolve) => {
resolvePut = resolve resolvePut = resolve
}) })
;(global as any).fetch = jest.fn(() => pendingPut) setRawFetchHandler((() => pendingPut) as any)
const view = renderProbe() const view = renderProbe()
expect(view.getByTestId('uploading').props.children).toBe('idle') expect(view.getByTestId('uploading').props.children).toBe('idle')

View file

@ -1,16 +1,28 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
/** /**
* Manual mock for `@/src/trpc-client`. * tRPC test harness — procedure registry + network-level mock.
* *
* Every backend procedure is a keyed entry in a registry. Tests set the outcome * The app's REAL `@/src/trpc-client` now runs in tests (real `httpBatchLink` +
* (`success` / `error` / `pending`), the payload, or a dynamic `impl`, then the * real React Query). This module only fakes the **network response**:
* page under test reads it through the same `trpc.<path>.useQuery/useMutation`
* surface it uses in production.
* *
* Call recording powers the catalogue's "assert the procedure name and exact * real hook -> real tRPC client -> global fetch (this mock) -> registry
* input" rule: `lastProcedureInput`, `procedureMutationCalls`, ... *
* `installTrpcNetworkMock()` replaces `global.fetch`. It parses the batch
* request the client builds:
*
* GET /api/trpc/a.b,c.d?batch=1&input={"0":…,"1":…}
* POST /api/trpc/a.b?batch=1 body {"0":…}
*
* and answers with the tRPC batch envelope, using the per-procedure registry:
*
* setProcedure('user.order.getOrders', { data: ORDERS_RESPONSE })
* setProcedure('user.auth.login', { mode: 'error', error: new Error('boom') })
* setProcedure('user.auth.login', { mode: 'pending' })
* setProcedure('user.auth.login', { impl: (input) => … })
*
* Call recording (`lastProcedureInput`, `procedureMutationCalls`, …) is filled
* from the same requests, so assertions keep working.
*/ */
import * as React from 'react'
import { defaultProcedures } from './trpc-defaults' import { defaultProcedures } from './trpc-defaults'
export type ProcedureMode = 'success' | 'error' | 'pending' export type ProcedureMode = 'success' | 'error' | 'pending'
@ -19,6 +31,8 @@ export interface ProcedureConfig {
mode?: ProcedureMode mode?: ProcedureMode
data?: any data?: any
error?: unknown error?: unknown
/** Optional tRPC error code override (default derived from `error.status`). */
errorCode?: string
impl?: (input: any) => any impl?: (input: any) => any
} }
@ -26,29 +40,25 @@ interface ProcedureRecord {
config: ProcedureConfig config: ProcedureConfig
queryCalls: any[] queryCalls: any[]
mutationCalls: any[] mutationCalls: any[]
invalidations: any[] }
export interface NetworkCall {
path: string
input: any
kind: 'query' | 'mutation'
authorization: string | null
} }
const procedures = new Map<string, ProcedureRecord>() const procedures = new Map<string, ProcedureRecord>()
let version = 0 const invalidations: string[] = []
const listeners = new Set<() => void>() const networkCalls: NetworkCall[] = []
let rawFetchHandler: ((url: string, init: any) => Promise<Response>) | null = null
function bump() { let installed = false
version += 1
listeners.forEach((listener) => listener())
}
function subscribe(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
const getVersion = () => version
function record(path: string): ProcedureRecord { function record(path: string): ProcedureRecord {
let entry = procedures.get(path) let entry = procedures.get(path)
if (!entry) { if (!entry) {
entry = { config: {}, queryCalls: [], mutationCalls: [], invalidations: [] } entry = { config: {}, queryCalls: [], mutationCalls: [] }
procedures.set(path, entry) procedures.set(path, entry)
} }
return entry return entry
@ -57,7 +67,6 @@ function record(path: string): ProcedureRecord {
export function setProcedure(path: string, config: ProcedureConfig) { export function setProcedure(path: string, config: ProcedureConfig) {
const entry = record(path) const entry = record(path)
entry.config = { ...entry.config, ...config } entry.config = { ...entry.config, ...config }
bump()
} }
export function setProcedures(map: Record<string, ProcedureConfig>) { export function setProcedures(map: Record<string, ProcedureConfig>) {
@ -65,13 +74,11 @@ export function setProcedures(map: Record<string, ProcedureConfig>) {
const entry = record(path) const entry = record(path)
entry.config = { ...entry.config, ...config } entry.config = { ...entry.config, ...config }
}) })
bump()
} }
export function clearProcedure(path: string) { export function clearProcedure(path: string) {
const entry = procedures.get(path) const entry = procedures.get(path)
if (entry) entry.config = {} if (entry) entry.config = {}
bump()
} }
export function getProcedureConfig(path: string): ProcedureConfig { export function getProcedureConfig(path: string): ProcedureConfig {
@ -84,8 +91,9 @@ export function seedDefaultProcedures() {
export function resetTrpcMocks() { export function resetTrpcMocks() {
procedures.clear() procedures.clear()
version = 0 invalidations.length = 0
listeners.clear() networkCalls.length = 0
rawFetchHandler = null
seedDefaultProcedures() seedDefaultProcedures()
} }
@ -97,8 +105,10 @@ export function procedureMutationCalls(path: string): any[] {
return [...(procedures.get(path)?.mutationCalls ?? [])] return [...(procedures.get(path)?.mutationCalls ?? [])]
} }
export function procedureInvalidations(path: string): any[] { /** Invalidation keys recorded from the real `queryClient.invalidateQueries`. */
return [...(procedures.get(path)?.invalidations ?? [])] export function procedureInvalidations(path: string): string[] {
if (path === 'root') return invalidations.filter((entry) => entry === 'root')
return invalidations.filter((entry) => entry === path)
} }
export function procedureCallCount(path: string): number { export function procedureCallCount(path: string): number {
@ -111,8 +121,7 @@ export function lastProcedureInput(path: string): any {
const entry = procedures.get(path) const entry = procedures.get(path)
if (!entry) return undefined if (!entry) return undefined
const all = [...entry.queryCalls, ...entry.mutationCalls] const all = [...entry.queryCalls, ...entry.mutationCalls]
if (all.length === 0) return undefined return all.length ? all[all.length - 1] : undefined
return all[all.length - 1]
} }
export function lastMutationInput(path: string): any { export function lastMutationInput(path: string): any {
@ -122,326 +131,165 @@ export function lastMutationInput(path: string): any {
export function expectProcedureCalled(path: string, times?: number) { export function expectProcedureCalled(path: string, times?: number) {
const count = procedureCallCount(path) const count = procedureCallCount(path)
if (times === undefined) { if (times === undefined) expect(count).toBeGreaterThan(0)
expect(count).toBeGreaterThan(0) else expect(count).toBe(times)
} else {
expect(count).toBe(times)
}
} }
export function expectNoProcedureCall(path: string) { export function expectNoProcedureCall(path: string) {
expect(procedureCallCount(path)).toBe(0) expect(procedureCallCount(path)).toBe(0)
} }
/** Every tRPC request the real client made (flattened across batches). */
export function recordedNetworkCalls(): NetworkCall[] {
return [...networkCalls]
}
export function lastNetworkCall(path?: string): NetworkCall | undefined {
const calls = path ? networkCalls.filter((call) => call.path === path) : networkCalls
return calls[calls.length - 1]
}
/** Override the response for non-tRPC fetches (uploads, etc.). */
export function setRawFetchHandler(handler: ((url: string, init: any) => Promise<Response>) | null) {
rawFetchHandler = handler
}
function recordInvalidationKey(queryKey: unknown) {
if (queryKey === undefined) {
invalidations.push('root')
return
}
if (Array.isArray(queryKey) && Array.isArray(queryKey[0])) {
invalidations.push((queryKey[0] as unknown[]).map(String).join('.'))
return
}
if (typeof queryKey === 'string') invalidations.push(queryKey)
}
/** Called by the test QueryClient wrapper. */
export function recordQueryInvalidation(filters: any) {
recordInvalidationKey(filters?.queryKey)
}
function resolveData(config: ProcedureConfig, input: any): any { function resolveData(config: ProcedureConfig, input: any): any {
if (config.impl) return config.impl(input) if (config.impl) return config.impl(input)
return config.data return config.data
} }
function useQueryImpl(path: string, input: any, options: any = {}) { const HTTP_STATUS_CODES: Record<number, string> = {
React.useSyncExternalStore(subscribe, getVersion, getVersion) 400: 'BAD_REQUEST',
401: 'UNAUTHORIZED',
const enabled = options?.enabled !== false 403: 'FORBIDDEN',
const entry = record(path) 404: 'NOT_FOUND',
const inputKey = JSON.stringify(input ?? null) 405: 'METHOD_NOT_SUPPORTED',
409: 'CONFLICT',
React.useEffect(() => { 422: 'UNPROCESSABLE_CONTENT',
if (enabled) entry.queryCalls.push(input) 429: 'TOO_MANY_REQUESTS',
// eslint-disable-next-line react-hooks/exhaustive-deps 500: 'INTERNAL_SERVER_ERROR',
}, [enabled, inputKey]) }
const config = entry.config
const mode = enabled ? config.mode ?? 'success' : 'success'
const isPending = enabled && mode === 'pending'
const isError = enabled && mode === 'error'
const error = isError ? config.error ?? new Error(`[trpc mock] ${path} failed`) : null
let data: any = undefined
if (enabled && !isPending && !isError) {
data = resolveData(config, input)
if (data === undefined) data = options?.placeholderData
if (options?.select && data !== undefined && data !== null) data = options.select(data)
}
function errorEntry(path: string, error: unknown, codeOverride?: string) {
const message = error instanceof Error ? error.message : String(error ?? 'Request failed')
const status = Number(
(error as { status?: number })?.status ??
(error as { httpStatus?: number })?.httpStatus ??
500
)
const httpStatus = Number.isFinite(status) && status >= 400 ? status : 500
const code = codeOverride ?? (error as { code?: string })?.code ?? HTTP_STATUS_CODES[httpStatus] ?? 'INTERNAL_SERVER_ERROR'
return { return {
data, error: {
error, message,
status: isPending ? 'pending' : isError ? 'error' : 'success', code: -32603,
isLoading: isPending, json: {
isPending, message,
isFetching: isPending, code: -32603,
isRefetching: false, data: { code, httpStatus, path },
isSuccess: enabled && !isPending && !isError, },
isError, },
isFetched: enabled && !isPending,
isFetchedAfterMount: enabled && !isPending,
isPlaceholderData: false,
isStale: false,
failureCount: isError ? 1 : 0,
failureReason: error,
dataUpdatedAt: 0,
errorUpdatedAt: 0,
refetch: jest.fn(async () => ({ data, error })),
} }
} }
function useInfiniteQueryImpl(path: string, input: any, options: any = {}) { function parseRequest(url: string, init: any) {
const base = useQueryImpl(path, input, options) const parsed = new URL(url)
const pages = base.data && Array.isArray((base.data as any).pages) ? (base.data as any).pages : [] const marker = '/api/trpc/'
return { const index = parsed.pathname.indexOf(marker)
...base, const rawPaths = index >= 0 ? parsed.pathname.slice(index + marker.length) : ''
data: base.data ? { pages, pageParams: pages.map((_: any, index: number) => index) } : undefined, const paths = rawPaths.split(',').filter(Boolean)
fetchNextPage: jest.fn(async () => undefined),
fetchPreviousPage: jest.fn(async () => undefined), const method = String(init?.method ?? 'GET').toUpperCase()
hasNextPage: false, let inputs: Record<string, any> = {}
hasPreviousPage: false, if (method === 'GET') {
isFetchingNextPage: false, const raw = parsed.searchParams.get('input')
isFetchingPreviousPage: false, if (raw) inputs = JSON.parse(raw)
} else if (typeof init?.body === 'string' && init.body.length > 0) {
inputs = JSON.parse(init.body)
} }
const headers = init?.headers ?? {}
const authorization =
(headers as any).Authorization ?? (headers as any).authorization ?? null
return { paths, method, inputs, authorization }
} }
function useMutationImpl(path: string, options: any = {}) { async function handleTrpcRequest(url: string, init: any): Promise<Response> {
React.useSyncExternalStore(subscribe, getVersion, getVersion) const { paths, method, inputs, authorization } = parseRequest(url, init)
const kind: 'query' | 'mutation' = method === 'GET' ? 'query' : 'mutation'
// Record every call first: a pending request is still a real request, and
// tests assert "exactly one request was made" even while the hook is loading.
const inputsByPath = paths.map((path, index) => {
const input = inputs[String(index)]
const entry = record(path) const entry = record(path)
const optionsRef = React.useRef(options) if (kind === 'query') entry.queryCalls.push(input)
optionsRef.current = options else entry.mutationCalls.push(input)
networkCalls.push({ path, input, kind, authorization })
return { path, input, entry }
})
const [state, setState] = React.useState<{ // `mode: 'pending'` keeps the whole batch (and therefore the hook) loading.
status: 'idle' | 'pending' | 'success' | 'error' if (paths.some((path) => getProcedureConfig(path).mode === 'pending')) {
data?: any return new Promise<Response>(() => {
error?: unknown
}>({ status: 'idle' })
const run = React.useCallback(
async (input: any) => {
entry.mutationCalls.push(input)
const current = optionsRef.current ?? {}
const config = entry.config
const mode = config.mode ?? 'success'
setState({ status: 'pending' })
if (mode === 'pending') {
return new Promise<any>(() => {
/* never settles */ /* never settles */
}) })
} }
if (mode === 'error') { const entries = inputsByPath.map(({ path, input, entry }) => {
const error = config.error ?? new Error(`[trpc mock] ${path} failed`) const config = entry.config
setState({ status: 'error', error }) if ((config.mode ?? 'success') === 'error') {
try { return errorEntry(path, config.error ?? new Error(`[trpc mock] ${path} failed`), config.errorCode)
current.onError?.(error, input, undefined)
} catch {
/* ignore */
} }
try { return { result: { data: resolveData(config, input) } }
current.onSettled?.(undefined, error, input, undefined) })
} catch {
/* ignore */ return new Response(JSON.stringify(entries), {
} status: 200,
throw error headers: { 'content-type': 'application/json' },
}
const data = resolveData(config, input)
setState({ status: 'success', data })
try {
current.onSuccess?.(data, input, undefined)
} catch {
/* ignore */
}
try {
current.onSettled?.(data, null, input, undefined)
} catch {
/* ignore */
}
return data
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[path]
)
const mutate = React.useCallback(
(input: any, mutateOptions?: any) => {
run(input).then(
(data) => mutateOptions?.onSuccess?.(data, input, undefined),
(error) => mutateOptions?.onError?.(error, input, undefined)
)
},
[run]
)
return {
mutate,
mutateAsync: run,
reset: () => setState({ status: 'idle' }),
data: state.data,
error: state.error,
status: state.status,
isPending: state.status === 'pending',
isLoading: state.status === 'pending',
isError: state.status === 'error',
isSuccess: state.status === 'success',
isIdle: state.status === 'idle',
failureCount: 0,
variables: undefined,
}
}
function queryNode(path: string): any {
return {
useQuery: (input?: any, options?: any) => useQueryImpl(path, input, options),
useInfiniteQuery: (input?: any, options?: any) => useInfiniteQueryImpl(path, input, options),
useMutation: (options?: any) => useMutationImpl(path, options),
}
}
function procedureNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
if (prop === 'useQuery' || prop === 'useInfiniteQuery' || prop === 'useMutation') {
return queryNode(path)[prop]
}
const next = path ? `${path}.${prop}` : prop
return procedureNode(next)
},
}
)
}
function recordInvalidation(path: string) {
const entry = record(path)
const spy = jest.fn(() => {
entry.invalidations.push({ path })
return Promise.resolve()
}) })
return spy
} }
function utilsNode(path: string): any { /**
return new Proxy( * Replace `global.fetch` with the tRPC-aware mock. Called once from
{}, * `tests/setup.ts`; the real client still builds the request.
{ */
get(_target, prop) { export function installTrpcNetworkMock() {
if (typeof prop !== 'string') return undefined if (installed) return
switch (prop) { installed = true
case 'invalidate': ;(global as any).fetch = jest.fn(async (input: any, init: any = {}) => {
return recordInvalidation(path) const url = typeof input === 'string' ? input : input?.url ?? String(input)
case 'refetch': if (!url.includes('/api/trpc')) {
return jest.fn(async () => ({ data: resolveData(getProcedureConfig(path), undefined) })) if (rawFetchHandler) return rawFetchHandler(url, init)
case 'fetch': return new Response(JSON.stringify({ ok: true }), {
return jest.fn(async (input?: any) => resolveData(getProcedureConfig(path), input)) status: 200,
case 'setData': headers: { 'content-type': 'application/json' },
return jest.fn() })
case 'getData':
return jest.fn(() => resolveData(getProcedureConfig(path), undefined))
case 'cancel':
return jest.fn(async () => undefined)
case 'remove':
return jest.fn()
case 'setInfiniteData':
return jest.fn()
case 'getInfiniteData':
return jest.fn(() => undefined)
case 'invalidateQueries':
return jest.fn(async () => undefined)
default:
return utilsNode(path ? `${path}.${prop}` : prop)
} }
}, return handleTrpcRequest(url, init)
} })
)
} }
const utilsProxy: any = new Proxy( /** True when `fetch` is the harness mock (useful in assertions). */
{}, export function isTrpcNetworkMockInstalled(): boolean {
{ return installed
get(_target, prop) {
if (typeof prop !== 'string') return undefined
if (prop === 'invalidate') return recordInvalidation('root')
if (prop === 'refetch') return jest.fn(async () => undefined)
if (prop === 'setData') return jest.fn()
if (prop === 'getData') return jest.fn(() => undefined)
if (prop === 'cancel') return jest.fn(async () => undefined)
if (prop === 'remove') return jest.fn()
if (prop === 'invalidateQueries') return jest.fn(async () => undefined)
return utilsNode(prop)
},
}
)
const TrpcProvider = ({ children }: { children?: React.ReactNode }) =>
React.createElement(React.Fragment, null, children)
function makeRootProxy(): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'Provider':
return TrpcProvider
case 'createClient':
return () => ({ __mockTrpcClient: true })
case 'useUtils':
return () => utilsProxy
case 'useContext':
return () => ({})
default:
return procedureNode(prop)
}
},
}
)
} }
export const trpc: any = makeRootProxy()
function clientNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'query':
return async (input?: any) => {
const entry = record(path)
entry.queryCalls.push(input)
const config = entry.config
if ((config.mode ?? 'success') === 'error') {
throw config.error ?? new Error(`[trpc mock] ${path} failed`)
}
return resolveData(config, input)
}
case 'mutate':
return async (input?: any) => {
const entry = record(path)
entry.mutationCalls.push(input)
const config = entry.config
if ((config.mode ?? 'success') === 'error') {
throw config.error ?? new Error(`[trpc mock] ${path} failed`)
}
return resolveData(config, input)
}
case 'subscribe':
return () => ({ unsubscribe: jest.fn() })
default:
return clientNode(path ? `${path}.${prop}` : prop)
}
},
}
)
}
export const trpcClient: any = clientNode('')
// Seed on import so components always have data unless a test overrides it.
seedDefaultProcedures()
export default { trpc, trpcClient }

View file

@ -4,7 +4,7 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import { ImageUploader } from 'common-ui' import { ImageUploader } from 'common-ui'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
@ -15,6 +15,7 @@ import {
setProcedure, setProcedure,
lastMutationInput, lastMutationInput,
procedureMutationCalls, procedureMutationCalls,
setRawFetchHandler,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
@ -44,7 +45,6 @@ function submit(view: View) {
describe('Banner create (ABANC-01..06)', () => { describe('Banner create (ABANC-01..06)', () => {
let alertSpy: jest.SpyInstance let alertSpy: jest.SpyInstance
let fetchSpy: jest.SpyInstance
beforeEach(() => { beforeEach(() => {
resetAllMocks() resetAllMocks()
@ -53,17 +53,17 @@ describe('Banner create (ABANC-01..06)', () => {
canceled: false, canceled: false,
assets: [{ uri: 'file:///banner.jpg', mimeType: 'image/jpeg', fileName: 'banner.jpg' }], assets: [{ uri: 'file:///banner.jpg', mimeType: 'image/jpeg', fileName: 'banner.jpg' }],
}) })
fetchSpy = jest.spyOn(global, 'fetch').mockImplementation((async (url: any) => { // Only non-tRPC traffic: reading the picked file and the presigned PUT.
if (String(url).startsWith('file://')) { setRawFetchHandler(async (url: string) => {
return { blob: async () => ({ size: 1 }) } if (url.startsWith('file://')) {
return { blob: async () => ({ size: 1 }) } as any
} }
return { ok: true, status: 200, text: async () => '' } return new Response('', { status: 200 })
}) as any) })
}) })
afterEach(() => { afterEach(() => {
alertSpy?.mockRestore() alertSpy?.mockRestore()
fetchSpy?.mockRestore()
}) })
it('ABANC-01: renders the create banner screen', () => { it('ABANC-01: renders the create banner screen', () => {
@ -91,7 +91,9 @@ describe('Banner create (ABANC-01..06)', () => {
await pickImage(view) await pickImage(view)
submit(view) submit(view)
await flush(4) await waitFor(() =>
expect(lastMutationInput('admin.banner.createBanner')).toBeTruthy()
)
const input = lastMutationInput('admin.banner.createBanner') const input = lastMutationInput('admin.banner.createBanner')
expect(input).toMatchObject({ expect(input).toMatchObject({
@ -99,11 +101,13 @@ describe('Banner create (ABANC-01..06)', () => {
imageUrl: 'https://upload.test/meatfarmer/product-images/img-1.jpg', imageUrl: 'https://upload.test/meatfarmer/product-images/img-1.jpg',
skuIds: [], skuIds: [],
}) })
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Success', 'Success',
'Banner created successfully', 'Banner created successfully',
expect.any(Array) expect.any(Array)
) )
)
}) })
it('ABANC-04: a failed create shows an error alert', async () => { it('ABANC-04: a failed create shows an error alert', async () => {
@ -113,9 +117,9 @@ describe('Banner create (ABANC-01..06)', () => {
await pickImage(view) await pickImage(view)
submit(view) submit(view)
await flush(4) await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to create banner. Please try again.') expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to create banner. Please try again.')
)
}) })
it('ABANC-05: Cancel goes back', () => { it('ABANC-05: Cancel goes back', () => {

View file

@ -4,20 +4,20 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import EditBanner from '@/app/(drawer)/dashboard/dashboard-banners/edit/[id]' import EditBanner from '@/app/(drawer)/dashboard/dashboard-banners/edit/[id]'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput } from '../mocks/trpc-client' import { setProcedure, lastMutationInput } from '../mocks/trpc-client'
import { router, __setParams } from '../mocks/expo-router-mock' import { router, __setParams } from '../mocks/expo-router-mock'
import { BANNER_1 } from '../fixtures' import { BANNER_1 } from '../fixtures'
type View = ReturnType<typeof renderEdit>['view'] type View = Awaited<ReturnType<typeof renderEdit>>['view']
function renderEdit(params: Record<string, string> = { id: '1' }) { async function renderEdit(params: Record<string, string> = { id: '1' }) {
__setParams(params) __setParams(params)
const view = renderWithProviders(<EditBanner />, { auth: false }) const view = await renderAndFlush(<EditBanner />, { auth: false })
return { view } return { view }
} }
@ -48,7 +48,7 @@ describe('Banner edit (ABANE-01..08)', () => {
it('ABANE-01: a pending banner query falls back to the not-found flow', async () => { it('ABANE-01: a pending banner query falls back to the not-found flow', async () => {
setProcedure('admin.banner.getBanner', { mode: 'pending' }) setProcedure('admin.banner.getBanner', { mode: 'pending' })
const { view } = renderEdit() const { view } = await renderEdit()
await flush(2) await flush(2)
// The screen does not wire the query's loading state; it renders its // The screen does not wire the query's loading state; it renders its
@ -58,36 +58,35 @@ describe('Banner edit (ABANE-01..08)', () => {
expect(view.getByText('Banner not found')).toBeTruthy() expect(view.getByText('Banner not found')).toBeTruthy()
}) })
it('ABANE-02: a missing banner alerts and goes back', () => { it('ABANE-02: a missing banner alerts and goes back', async () => {
setProcedure('admin.banner.getBanner', { data: null }) setProcedure('admin.banner.getBanner', { data: null })
const { view } = renderEdit() const { view } = await renderEdit()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Banner not found') expect(alertSpy).toHaveBeenCalledWith('Error', 'Banner not found')
expect(router.back).toHaveBeenCalled() expect(router.back).toHaveBeenCalled()
expect(view.getByText('Banner not found')).toBeTruthy() expect(view.getByText('Banner not found')).toBeTruthy()
}) })
it('ABANE-03: prefills name, description, image, products and redirect', () => { it('ABANE-03: prefills name, description, image, products and redirect', async () => {
setProcedure('admin.banner.getBanner', { data: bannerData() }) setProcedure('admin.banner.getBanner', { data: bannerData() })
const { view } = renderEdit() const { view } = await renderEdit()
expect(view.getByPlaceholderText('Enter banner name').props.value).toBe('Dash Banner') expect(view.getByPlaceholderText('Enter banner name').props.value).toBe('Dash Banner')
expect(view.getByPlaceholderText('Enter banner description (optional)').props.value).toBe( expect(view.getByPlaceholderText('Enter banner description (optional)').props.value).toBe(
'Top banner' 'Top banner'
) )
expect(view.getByPlaceholderText('https://example.com/redirect').props.value).toBe('') expect(view.getByPlaceholderText('https://example.com/redirect').props.value).toBe('')
expect(view.getByText('Chicken Breast (₹215)')).toBeTruthy() expect(await view.findByText('Chicken Breast (₹215)')).toBeTruthy()
expect(view.getAllByLabelText('https://assets.test/banner1.jpg').length).toBeGreaterThan(0) expect(view.getAllByLabelText('https://assets.test/banner1.jpg').length).toBeGreaterThan(0)
}) })
it('ABANE-04: saving calls updateBanner with the full payload and goes back on OK', async () => { it('ABANE-04: saving calls updateBanner with the full payload and goes back on OK', async () => {
setProcedure('admin.banner.getBanner', { data: bannerData() }) setProcedure('admin.banner.getBanner', { data: bannerData() })
const { view } = renderEdit() const { view } = await renderEdit()
fireEvent.changeText(view.getByPlaceholderText('Enter banner name'), 'Renamed Banner') fireEvent.changeText(view.getByPlaceholderText('Enter banner name'), 'Renamed Banner')
submit(view) submit(view)
await flush(3) await waitFor(() =>
expect(lastMutationInput('admin.banner.updateBanner')).toMatchObject({ expect(lastMutationInput('admin.banner.updateBanner')).toMatchObject({
id: 1, id: 1,
name: 'Renamed Banner', name: 'Renamed Banner',
@ -95,11 +94,14 @@ describe('Banner edit (ABANE-01..08)', () => {
description: 'Top banner', description: 'Top banner',
skuIds: [11], skuIds: [11],
}) })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Success', 'Success',
'Banner updated successfully', 'Banner updated successfully',
expect.any(Array) expect.any(Array)
) )
)
const buttons = alertSpy.mock.calls.find((call) => call[0] === 'Success')[2] const buttons = alertSpy.mock.calls.find((call) => call[0] === 'Success')[2]
act(() => { act(() => {
@ -111,18 +113,18 @@ describe('Banner edit (ABANE-01..08)', () => {
it('ABANE-05: a failed update shows an error alert', async () => { it('ABANE-05: a failed update shows an error alert', async () => {
setProcedure('admin.banner.getBanner', { data: bannerData() }) setProcedure('admin.banner.getBanner', { data: bannerData() })
setProcedure('admin.banner.updateBanner', { mode: 'error', error: new Error('no') }) setProcedure('admin.banner.updateBanner', { mode: 'error', error: new Error('no') })
const { view } = renderEdit() const { view } = await renderEdit()
fireEvent.changeText(view.getByPlaceholderText('Enter banner name'), 'Renamed') fireEvent.changeText(view.getByPlaceholderText('Enter banner name'), 'Renamed')
submit(view) submit(view)
await flush(3) await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to update banner. Please try again.') expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to update banner. Please try again.')
)
}) })
it('ABANE-06: missing route id with no banner alerts and goes back', async () => { it('ABANE-06: missing route id with no banner alerts and goes back', async () => {
setProcedure('admin.banner.getBanner', { data: null }) setProcedure('admin.banner.getBanner', { data: null })
const { view } = renderEdit({}) const { view } = await renderEdit({})
await flush() await flush()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Banner not found') expect(alertSpy).toHaveBeenCalledWith('Error', 'Banner not found')
@ -132,23 +134,23 @@ describe('Banner edit (ABANE-01..08)', () => {
it('ABANE-07: removing an existing image is not wired; the original is kept', async () => { it('ABANE-07: removing an existing image is not wired; the original is kept', async () => {
setProcedure('admin.banner.getBanner', { data: bannerData() }) setProcedure('admin.banner.getBanner', { data: bannerData() })
const { view } = renderEdit() const { view } = await renderEdit()
// ImageUploader renders the existing image but BannerForm's // ImageUploader renders the existing image but BannerForm's
// onRemoveExistingImage is a no-op, so the stored URL survives the save. // onRemoveExistingImage is a no-op, so the stored URL survives the save.
expect(view.getAllByLabelText('https://assets.test/banner1.jpg').length).toBeGreaterThan(0) expect(view.getAllByLabelText('https://assets.test/banner1.jpg').length).toBeGreaterThan(0)
fireEvent.changeText(view.getByPlaceholderText('Enter banner name'), 'Still Has Image') fireEvent.changeText(view.getByPlaceholderText('Enter banner name'), 'Still Has Image')
submit(view) submit(view)
await flush(3) await waitFor(() =>
expect(lastMutationInput('admin.banner.updateBanner').imageUrl).toBe( expect(lastMutationInput('admin.banner.updateBanner').imageUrl).toBe(
'https://assets.test/banner1.jpg' 'https://assets.test/banner1.jpg'
) )
)
}) })
it('ABANE-08: Cancel goes back', () => { it('ABANE-08: Cancel goes back', async () => {
setProcedure('admin.banner.getBanner', { data: bannerData() }) setProcedure('admin.banner.getBanner', { data: bannerData() })
const { view } = renderEdit() const { view } = await renderEdit()
fireEvent.press(view.getByText('Cancel')) fireEvent.press(view.getByText('Cancel'))

View file

@ -4,11 +4,11 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, StyleSheet } from 'react-native' import { Alert, StyleSheet } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import { MaterialIcons } from '@expo/vector-icons' import { MaterialIcons } from '@expo/vector-icons'
import DashboardBanners from '@/app/(drawer)/dashboard/dashboard-banners/index' import DashboardBanners from '@/app/(drawer)/dashboard/dashboard-banners/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -18,7 +18,7 @@ import {
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { BANNER_1 } from '../fixtures' import { BANNER_1 } from '../fixtures'
type View = ReturnType<typeof renderBanners>['view'] type View = Awaited<ReturnType<typeof renderBanners>>['view']
function banner(over: Partial<any> = {}) { function banner(over: Partial<any> = {}) {
return { return {
@ -30,9 +30,26 @@ function banner(over: Partial<any> = {}) {
} }
} }
function renderBanners(banners = [banner()]) { async function renderBanners(banners = [banner()], options: { stateful?: boolean } = {}) {
if (options.stateful) {
// Model the backend: updateBanner changes the row, so the real refetch that
// follows a save returns the banner in its new slot.
let stored = banners
setProcedure('admin.banner.getBanners', {
impl: () => ({ banners: stored, count: stored.length }),
})
setProcedure('admin.banner.updateBanner', {
impl: (input: any) => {
stored = stored.map((row) =>
row.id === input.id ? { ...row, serialNum: input.serialNum } : row
)
return { banner: stored.find((row) => row.id === input.id) }
},
})
} else {
setProcedure('admin.banner.getBanners', { data: { banners, count: banners.length } }) setProcedure('admin.banner.getBanners', { data: { banners, count: banners.length } })
const view = renderWithProviders(<DashboardBanners />, { auth: false }) }
const view = await renderAndFlush(<DashboardBanners />, { auth: false })
return { view } return { view }
} }
@ -65,15 +82,15 @@ describe('Dashboard banners (ABANUI-01..20)', () => {
expect(view.getByText('Loading banners...')).toBeTruthy() expect(view.getByText('Loading banners...')).toBeTruthy()
}) })
it('ABANUI-02: shows the error copy', () => { it('ABANUI-02: shows the error copy', async () => {
setProcedure('admin.banner.getBanners', { mode: 'error', error: new Error('boom') }) setProcedure('admin.banner.getBanners', { mode: 'error', error: new Error('boom') })
const view = renderWithProviders(<DashboardBanners />, { auth: false }) const view = renderWithProviders(<DashboardBanners />, { auth: false })
expect(view.getByText('Error loading banners')).toBeTruthy() expect(await view.findByText('Error loading banners')).toBeTruthy()
}) })
it('ABANUI-03: shows the empty state', () => { it('ABANUI-03: shows the empty state', async () => {
const { view } = renderBanners([]) const { view } = await renderBanners([])
expect(view.getByText('No Banners Yet')).toBeTruthy() expect(view.getByText('No Banners Yet')).toBeTruthy()
expect( expect(
@ -81,8 +98,8 @@ describe('Dashboard banners (ABANUI-01..20)', () => {
).toBeTruthy() ).toBeTruthy()
}) })
it('ABANUI-04: renders the banner name, description and actions', () => { it('ABANUI-04: renders the banner name, description and actions', async () => {
const { view } = renderBanners([banner({ serialNum: 1 })]) const { view } = await renderBanners([banner({ serialNum: 1 })])
expect(view.getAllByText('Dash Banner').length).toBeGreaterThan(0) expect(view.getAllByText('Dash Banner').length).toBeGreaterThan(0)
expect(view.getByText('Top banner')).toBeTruthy() expect(view.getByText('Top banner')).toBeTruthy()
@ -92,30 +109,30 @@ describe('Dashboard banners (ABANUI-01..20)', () => {
expect(icon(view, 'delete')).toBeTruthy() expect(icon(view, 'delete')).toBeTruthy()
}) })
it('ABANUI-05: an inactive banner uses the grey status dot', () => { it('ABANUI-05: an inactive banner uses the grey status dot', async () => {
const { view } = renderBanners([banner({ isActive: false })]) const { view } = await renderBanners([banner({ isActive: false })])
const style = StyleSheet.flatten(view.getByTestId('banner-status-1').props.style) const style = StyleSheet.flatten(view.getByTestId('banner-status-1').props.style)
expect(style.backgroundColor).toBe('#9ca3af') expect(style.backgroundColor).toBe('#9ca3af')
}) })
it('ABANUI-06: an active banner uses the green status dot', () => { it('ABANUI-06: an active banner uses the green status dot', async () => {
const { view } = renderBanners([banner({ isActive: true })]) const { view } = await renderBanners([banner({ isActive: true })])
const style = StyleSheet.flatten(view.getByTestId('banner-status-1').props.style) const style = StyleSheet.flatten(view.getByTestId('banner-status-1').props.style)
expect(style.backgroundColor).toBe('#22c55e') expect(style.backgroundColor).toBe('#22c55e')
}) })
it('ABANUI-07: Add New Banner opens the create route', () => { it('ABANUI-07: Add New Banner opens the create route', async () => {
const { view } = renderBanners() const { view } = await renderBanners()
fireEvent.press(view.getByLabelText('Add new banner')) fireEvent.press(view.getByLabelText('Add new banner'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/dashboard-banners/create') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/dashboard-banners/create')
}) })
it('ABANUI-08: the edit icon opens the edit route', () => { it('ABANUI-08: the edit icon opens the edit route', async () => {
const { view } = renderBanners() const { view } = await renderBanners()
fireEvent.press(icon(view, 'edit')) fireEvent.press(icon(view, 'edit'))
@ -123,7 +140,7 @@ describe('Dashboard banners (ABANUI-01..20)', () => {
}) })
it('ABANUI-09: delete confirms, calls the mutation and reports success/failure', async () => { it('ABANUI-09: delete confirms, calls the mutation and reports success/failure', async () => {
const { view } = renderBanners() const { view } = await renderBanners()
fireEvent.press(icon(view, 'delete')) fireEvent.press(icon(view, 'delete'))
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
@ -143,8 +160,8 @@ describe('Dashboard banners (ABANUI-01..20)', () => {
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to delete banner') expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to delete banner')
}) })
it('ABANUI-10: selecting a slot then a banner enters assignment mode', () => { it('ABANUI-10: selecting a slot then a banner enters assignment mode', async () => {
const { view } = renderBanners() const { view } = await renderBanners()
fireEvent.press(view.getByText('Slot 1')) fireEvent.press(view.getByText('Slot 1'))
expect(view.getByText('Select banner for Slot 1')).toBeTruthy() expect(view.getByText('Select banner for Slot 1')).toBeTruthy()
@ -155,35 +172,33 @@ describe('Dashboard banners (ABANUI-01..20)', () => {
}) })
it('ABANUI-11: Save Changes calls updateBanner and succeeds', async () => { it('ABANUI-11: Save Changes calls updateBanner and succeeds', async () => {
const { view } = renderBanners() const { view } = await renderBanners()
fireEvent.press(view.getByText('Slot 1')) fireEvent.press(view.getByText('Slot 1'))
fireEvent.press(view.getByText('Dash Banner')) fireEvent.press(view.getByText('Dash Banner'))
await act(async () => {
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
}) await waitFor(() =>
await flush(2)
expect(lastMutationInput('admin.banner.updateBanner')).toEqual({ id: 1, serialNum: 1 }) expect(lastMutationInput('admin.banner.updateBanner')).toEqual({ id: 1, serialNum: 1 })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot assignments saved successfully') expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot assignments saved successfully')
)
}) })
it('ABANUI-12: a failed assignment save shows an error alert', async () => { it('ABANUI-12: a failed assignment save shows an error alert', async () => {
setProcedure('admin.banner.updateBanner', { mode: 'error', error: new Error('no') }) setProcedure('admin.banner.updateBanner', { mode: 'error', error: new Error('no') })
const { view } = renderBanners() const { view } = await renderBanners()
fireEvent.press(view.getByText('Slot 1')) fireEvent.press(view.getByText('Slot 1'))
fireEvent.press(view.getByText('Dash Banner')) fireEvent.press(view.getByText('Dash Banner'))
await act(async () => {
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
}) await waitFor(() =>
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to save slot assignments') expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to save slot assignments')
)
}) })
it('ABANUI-13: Cancel leaves assignment mode and restores the slot', () => { it('ABANUI-13: Cancel leaves assignment mode and restores the slot', async () => {
const { view } = renderBanners() const { view } = await renderBanners()
fireEvent.press(view.getByText('Slot 1')) fireEvent.press(view.getByText('Slot 1'))
fireEvent.press(view.getByText('Dash Banner')) fireEvent.press(view.getByText('Dash Banner'))
@ -194,77 +209,77 @@ describe('Dashboard banners (ABANUI-01..20)', () => {
}) })
it('ABANUI-14: Empty Slot clears serialNum and reports success/failure', async () => { it('ABANUI-14: Empty Slot clears serialNum and reports success/failure', async () => {
const { view } = renderBanners([banner({ serialNum: 1 })]) const { view } = await renderBanners([banner({ serialNum: 1 })], { stateful: true })
fireEvent.press(view.getAllByText('Slot 1')[0]) fireEvent.press(view.getAllByText('Slot 1')[0])
await act(async () => {
fireEvent.press(view.getByText('Empty Slot')) fireEvent.press(view.getByText('Empty Slot'))
}) await waitFor(() =>
await flush(2)
expect(lastMutationInput('admin.banner.updateBanner')).toEqual({ id: 1, serialNum: null }) expect(lastMutationInput('admin.banner.updateBanner')).toEqual({ id: 1, serialNum: null })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot 1 has been emptied') expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot 1 has been emptied')
)
alertSpy.mockClear() alertSpy.mockClear()
setProcedure('admin.banner.updateBanner', { mode: 'error', error: new Error('no') }) setProcedure('admin.banner.updateBanner', { mode: 'error', error: new Error('no') })
// Re-assign the banner to the still-selected slot, then try to empty it. // Re-assign the banner to the still-selected slot, then try to empty it.
fireEvent.press(view.getAllByText('Dash Banner')[0]) fireEvent.press(view.getAllByText('Dash Banner')[0])
await act(async () => {
fireEvent.press(view.getByText('Empty Slot')) fireEvent.press(view.getByText('Empty Slot'))
}) await waitFor(() =>
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to empty slot') expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to empty slot')
)
}) })
it('ABANUI-15: renders four fixed slots', () => { it('ABANUI-15: renders four fixed slots', async () => {
const { view } = renderBanners([]) const { view } = await renderBanners([])
expect(view.getAllByText(/^Slot [1-4]$/)).toHaveLength(4) expect(view.getAllByText(/^Slot [1-4]$/)).toHaveLength(4)
}) })
it('ABANUI-16: a banner assigned to a slot is labelled on its row', () => { it('ABANUI-16: a banner assigned to a slot is labelled on its row', async () => {
const { view } = renderBanners([banner({ serialNum: 1 })]) const { view } = await renderBanners([banner({ serialNum: 1 })])
expect(view.getAllByText('Slot 1').length).toBeGreaterThanOrEqual(2) expect(view.getAllByText('Slot 1').length).toBeGreaterThanOrEqual(2)
}) })
it('ABANUI-17: a banner without an image still renders', () => { it('ABANUI-17: a banner without an image still renders', async () => {
const { view } = renderBanners([banner({ imageUrl: null })]) const { view } = await renderBanners([banner({ imageUrl: null })])
expect(view.getByText('Dash Banner')).toBeTruthy() expect(view.getByText('Dash Banner')).toBeTruthy()
expect(view.getByText('Top banner')).toBeTruthy() expect(view.getByText('Top banner')).toBeTruthy()
}) })
it('ABANUI-18: long banner names are clamped to one line', () => { it('ABANUI-18: long banner names are clamped to one line', async () => {
const longName = 'A'.repeat(140) const longName = 'A'.repeat(140)
const { view } = renderBanners([banner({ name: longName })]) const { view } = await renderBanners([banner({ name: longName })])
expect(view.getByText(longName).props.numberOfLines).toBe(1) expect(view.getByText(longName).props.numberOfLines).toBe(1)
}) })
it('ABANUI-19: assignment and empty-slot paths each call updateBanner', async () => { it('ABANUI-19: assignment and empty-slot paths each call updateBanner', async () => {
const { view } = renderBanners() const { view } = await renderBanners([banner()], { stateful: true })
fireEvent.press(view.getByText('Slot 2')) fireEvent.press(view.getByText('Slot 2'))
fireEvent.press(view.getByText('Dash Banner')) fireEvent.press(view.getByText('Dash Banner'))
await act(async () => {
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
}) await waitFor(() =>
await flush(2)
expect(lastMutationInput('admin.banner.updateBanner')).toEqual({ id: 1, serialNum: 2 }) expect(lastMutationInput('admin.banner.updateBanner')).toEqual({ id: 1, serialNum: 2 })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot assignments saved successfully')
)
fireEvent.press(view.getByText('Slot 2')) fireEvent.press(view.getAllByText('Slot 2')[0])
await act(async () => {
fireEvent.press(view.getByText('Empty Slot')) fireEvent.press(view.getByText('Empty Slot'))
}) await waitFor(() =>
await flush(2)
expect(lastMutationInput('admin.banner.updateBanner')).toEqual({ id: 1, serialNum: null }) expect(lastMutationInput('admin.banner.updateBanner')).toEqual({ id: 1, serialNum: null })
)
expect(procedureMutationCalls('admin.banner.updateBanner').length).toBeGreaterThanOrEqual(2) expect(procedureMutationCalls('admin.banner.updateBanner').length).toBeGreaterThanOrEqual(2)
}) })
it('ABANUI-20: image loading state renders without crashing', () => { it('ABANUI-20: image loading state renders without crashing', async () => {
const { view } = renderBanners([banner({ imageUrl: 'https://assets.test/loading.jpg' })]) const { view } = await renderBanners([banner({ imageUrl: 'https://assets.test/loading.jpg' })])
expect(view.getByText('Dash Banner')).toBeTruthy() expect(view.getByText('Dash Banner')).toBeTruthy()
expect(view.getByTestId('banner-status-1')).toBeTruthy() expect(view.getByTestId('banner-status-1')).toBeTruthy()

View file

@ -6,74 +6,25 @@
* flattens each row to {text, userName, userMobile, status, images, response}. * flattens each row to {text, userName, userMobile, status, images, response}.
* Tests build that page shape locally (see COMPLAINT_PAGE_*). * Tests build that page shape locally (see COMPLAINT_PAGE_*).
* *
* Harness workaround (reported): the shared trpc mock pins `hasNextPage=false` * The real `useInfiniteQuery` runs here: retry/focus/resolve refetches are
* and hands back a throw-away `fetchNextPage`/`refetch`, so pagination and * observed through the recorded procedure calls, and ACOMPUI-13 serves a real
* refresh rows cannot be observed. This file wraps the same procedure registry * second page (cursor) so `fetchNextPage` appends through the real hook.
* locally and exposes those two spies without touching the harness.
*/ */
import React from 'react' import React from 'react'
import { Alert, FlatList, Image, Modal, RefreshControl } from 'react-native' import { Alert, FlatList, Image, Modal, RefreshControl } from 'react-native'
import { act, fireEvent, waitFor } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import Complaints from '@/app/(drawer)/dashboard/complaints/index' import Complaints from '@/app/(drawer)/dashboard/complaints/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
procedureMutationCalls, procedureMutationCalls,
procedureQueryCalls,
setProcedure, setProcedure,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
jest.mock('../mocks/trpc-client', () => {
const actual = jest.requireActual('../mocks/trpc-client')
const paginationState = { fetchingNextPage: false }
const fetchNextPage = jest.fn()
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 === 'useInfiniteQuery' && path === 'admin.complaint.getAll') {
return (input: any, options: any) => {
const result = nodeFor(path).useInfiniteQuery(input, options)
const pages = result.data?.pages ?? []
const lastPage = pages[pages.length - 1]
return {
...result,
refetch,
fetchNextPage,
hasNextPage: Boolean(lastPage?.nextCursor),
isFetchingNextPage: paginationState.fetchingNextPage,
}
}
}
if (prop === 'useQuery' || prop === 'useMutation' || prop === 'useInfiniteQuery') {
return nodeFor(path)[prop]
}
return wrap(path ? `${path}.${prop}` : prop)
},
}
)
return {
...actual,
trpc: wrap(''),
__paginationState: paginationState,
__fetchNextPage: fetchNextPage,
__refetch: refetch,
}
})
// Focus simulation: the shared @react-navigation mock never re-runs the focus // Focus simulation: the shared @react-navigation mock never re-runs the focus
// effect, so `useMarkDataFetchers` can never be observed. This local mock keeps // effect, so `useMarkDataFetchers` can never be observed. This local mock keeps
// the real module and adds a manual `__triggerFocus`. // the real module and adds a manual `__triggerFocus`.
@ -101,7 +52,6 @@ jest.mock('@react-navigation/native', () => {
} }
}) })
const trpcMock = require('../mocks/trpc-client') as any
const navMock = require('@react-navigation/native') as any const navMock = require('@react-navigation/native') as any
const COMPLAINT = (over: Record<string, any> = {}) => ({ const COMPLAINT = (over: Record<string, any> = {}) => ({
@ -129,12 +79,28 @@ const COMPLAINT_RESOLVED = COMPLAINT({
response: 'We fixed it', response: 'We fixed it',
}) })
function setComplaintPages(pages: Array<{ complaints: any[]; nextCursor?: number }>) { function setComplaintPage(page: { complaints: any[]; nextCursor?: number }) {
setProcedure('admin.complaint.getAll', { data: { pages } }) 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() { function renderComplaints() {
return renderWithProviders(<Complaints />, { auth: 'in' }) return renderAndFlush(<Complaints />, { auth: 'in' })
} }
describe('Complaints (ACOMPUI-01..16)', () => { describe('Complaints (ACOMPUI-01..16)', () => {
@ -150,7 +116,7 @@ describe('Complaints (ACOMPUI-01..16)', () => {
it('ACOMPUI-01: shows "Loading complaints..." while the query is pending', () => { it('ACOMPUI-01: shows "Loading complaints..." while the query is pending', () => {
setProcedure('admin.complaint.getAll', { mode: 'pending' }) setProcedure('admin.complaint.getAll', { mode: 'pending' })
const view = renderComplaints() const view = renderWithProviders(<Complaints />, { auth: 'in' })
expect(view.getByText('Loading complaints...')).toBeTruthy() expect(view.getByText('Loading complaints...')).toBeTruthy()
}) })
@ -158,31 +124,30 @@ describe('Complaints (ACOMPUI-01..16)', () => {
it('ACOMPUI-02: a failed query shows Error + Retry and Retry refetches', async () => { it('ACOMPUI-02: a failed query shows Error + Retry and Retry refetches', async () => {
setProcedure('admin.complaint.getAll', { mode: 'error', error: new Error('boom') }) setProcedure('admin.complaint.getAll', { mode: 'error', error: new Error('boom') })
const view = renderComplaints() const view = await renderComplaints()
await flush()
expect(view.getByText('Error')).toBeTruthy() expect(view.getByText('Error')).toBeTruthy()
expect(view.getByText('boom')).toBeTruthy() expect(view.getByText('boom')).toBeTruthy()
const calls = queryCallCount()
fireEvent.press(view.getByText('Retry')) fireEvent.press(view.getByText('Retry'))
expect(trpcMock.__refetch).toHaveBeenCalled() await waitFor(() => expect(queryCallCount()).toBe(calls + 1))
}) })
it('ACOMPUI-03: an empty page renders the empty copy', async () => { it('ACOMPUI-03: an empty page renders the empty copy', async () => {
setComplaintPages([{ complaints: [] }]) setComplaintPage({ complaints: [] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
expect(view.getByText('No complaints')).toBeTruthy() expect(view.getByText('No complaints')).toBeTruthy()
expect(view.getByText('All complaints will appear here')).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 () => { it('ACOMPUI-04: a card shows id, user, order, text, status, images and response', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING, COMPLAINT_RESOLVED] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING, COMPLAINT_RESOLVED] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
expect(view.getByText('Complaint #1')).toBeTruthy() expect(view.getByText('Complaint #1')).toBeTruthy()
expect(view.getByText('Late delivery')).toBeTruthy() expect(view.getByText('Late delivery')).toBeTruthy()
@ -198,30 +163,27 @@ describe('Complaints (ACOMPUI-01..16)', () => {
}) })
it('ACOMPUI-05: a pending complaint shows the Pending status + resolve button', async () => { it('ACOMPUI-05: a pending complaint shows the Pending status + resolve button', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
expect(view.getByText('Pending')).toBeTruthy() expect(view.getByText('Pending')).toBeTruthy()
expect(view.getByText('Resolve Complaint')).toBeTruthy() expect(view.getByText('Resolve Complaint')).toBeTruthy()
}) })
it('ACOMPUI-06: a resolved complaint shows the Resolved status and hides resolve', async () => { it('ACOMPUI-06: a resolved complaint shows the Resolved status and hides resolve', async () => {
setComplaintPages([{ complaints: [COMPLAINT_RESOLVED] }]) setComplaintPage({ complaints: [COMPLAINT_RESOLVED] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
expect(view.getByText('Resolved')).toBeTruthy() expect(view.getByText('Resolved')).toBeTruthy()
expect(view.queryByText('Resolve Complaint')).toBeNull() expect(view.queryByText('Resolve Complaint')).toBeNull()
}) })
it('ACOMPUI-07: pressing the user opens the user detail route', async () => { it('ACOMPUI-07: pressing the user opens the user detail route', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
fireEvent.press(view.getByText('Test User')) fireEvent.press(view.getByText('Test User'))
@ -229,10 +191,9 @@ describe('Complaints (ACOMPUI-01..16)', () => {
}) })
it('ACOMPUI-08: pressing the order opens the order detail route', async () => { it('ACOMPUI-08: pressing the order opens the order detail route', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
fireEvent.press(view.getByText('Order #11')) fireEvent.press(view.getByText('Order #11'))
@ -240,10 +201,9 @@ describe('Complaints (ACOMPUI-01..16)', () => {
}) })
it('ACOMPUI-09: Mark resolved opens the confirmation dialog with a comment field', async () => { it('ACOMPUI-09: Mark resolved opens the confirmation dialog with a comment field', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
fireEvent.press(view.getByText('Resolve Complaint')) fireEvent.press(view.getByText('Resolve Complaint'))
@ -254,85 +214,80 @@ describe('Complaints (ACOMPUI-01..16)', () => {
}) })
it('ACOMPUI-10: an empty comment still submits (server min(1) is the only guard)', async () => { it('ACOMPUI-10: an empty comment still submits (server min(1) is the only guard)', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
fireEvent.press(view.getByText('Resolve Complaint')) fireEvent.press(view.getByText('Resolve Complaint'))
fireEvent.press(view.getByText('Resolve')) fireEvent.press(view.getByText('Resolve'))
await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.complaint.resolve')).toEqual({ id: '1', response: '' }) expect(lastMutationInput('admin.complaint.resolve')).toEqual({ id: '1', response: '' })
)
expect(procedureMutationCalls('admin.complaint.resolve')).toHaveLength(1) expect(procedureMutationCalls('admin.complaint.resolve')).toHaveLength(1)
}) })
it('ACOMPUI-11: resolving sends the comment, alerts success and refetches', async () => { it('ACOMPUI-11: resolving sends the comment, alerts success and refetches', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = renderComplaints() const view = await renderComplaints()
await flush() const calls = queryCallCount()
fireEvent.press(view.getByText('Resolve Complaint')) fireEvent.press(view.getByText('Resolve Complaint'))
fireEvent.changeText(view.getByPlaceholderText('Add a comment...'), 'Fixed') fireEvent.changeText(view.getByPlaceholderText('Add a comment...'), 'Fixed')
fireEvent.press(view.getByText('Resolve')) fireEvent.press(view.getByText('Resolve'))
await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.complaint.resolve')).toEqual({ id: '1', response: 'Fixed' }) expect(lastMutationInput('admin.complaint.resolve')).toEqual({ id: '1', response: 'Fixed' })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Complaint marked as resolved') expect(alertSpy).toHaveBeenCalledWith('Success', 'Complaint marked as resolved')
expect(trpcMock.__refetch).toHaveBeenCalled() )
await waitFor(() => expect(queryCallCount()).toBeGreaterThan(calls))
expect(view.queryByText('Add admin notes for this resolution:')).toBeNull() expect(view.queryByText('Add admin notes for this resolution:')).toBeNull()
}) })
it('ACOMPUI-12: a failed resolve alerts the error and closes the dialog', async () => { it('ACOMPUI-12: a failed resolve alerts the error and closes the dialog', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
setProcedure('admin.complaint.resolve', { mode: 'error', error: new Error('nope') }) setProcedure('admin.complaint.resolve', { mode: 'error', error: new Error('nope') })
const view = renderComplaints() const view = await renderComplaints()
await flush()
fireEvent.press(view.getByText('Resolve Complaint')) fireEvent.press(view.getByText('Resolve Complaint'))
fireEvent.changeText(view.getByPlaceholderText('Add a comment...'), 'Fixed') fireEvent.changeText(view.getByPlaceholderText('Add a comment...'), 'Fixed')
fireEvent.press(view.getByText('Resolve')) fireEvent.press(view.getByText('Resolve'))
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'nope') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope'))
await waitFor(() =>
expect(view.queryByText('Add admin notes for this resolution:')).toBeNull() 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 () => { it('ACOMPUI-13: end of list calls fetchNextPage and the appended page is rendered', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING], nextCursor: 1 }]) setPagedComplaints()
const view = renderComplaints() const view = await renderComplaints()
await flush()
expect(view.getByText('Complaint #1')).toBeTruthy() expect(view.getByText('Complaint #1')).toBeTruthy()
const list = view.UNSAFE_getByType(FlatList) const list = view.UNSAFE_getByType(FlatList)
await act(async () => { await act(async () => {
list.props.onEndReached?.({ distanceFromEnd: 0 }) await list.props.onEndReached?.({ distanceFromEnd: 0 })
}) })
expect(trpcMock.__fetchNextPage).toHaveBeenCalled() // The real infinite query requested the next page with the cursor.
await waitFor(() => expect(queryCallCount()).toBeGreaterThanOrEqual(2))
// The harness mock never appends; feed the second page directly and assert const calls = procedureQueryCalls('admin.complaint.getAll')
// it is flattened into the same list (deduped by id). expect(calls[calls.length - 1]).toMatchObject({ limit: 20, cursor: 1 })
await act(async () => {
setComplaintPages([
{ complaints: [COMPLAINT_PENDING, COMPLAINT_RESOLVED], nextCursor: undefined },
])
})
await flush()
await waitFor(() => expect(view.getByText('Complaint #2')).toBeTruthy())
expect(view.getByText('Complaint #1')).toBeTruthy() expect(view.getByText('Complaint #1')).toBeTruthy()
expect(view.getByText('Complaint #2')).toBeTruthy()
}) })
it('ACOMPUI-14: pull-to-refresh triggers the shared refresh (query cache clear)', async () => { it('ACOMPUI-14: pull-to-refresh triggers the shared refresh (query cache clear)', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
const clearSpy = jest.spyOn(view.queryClient, 'clear') const clearSpy = jest.spyOn(view.queryClient, 'clear')
const refresh = view.UNSAFE_getByType(RefreshControl) const refresh = view.UNSAFE_getByType(RefreshControl)
@ -344,26 +299,23 @@ describe('Complaints (ACOMPUI-01..16)', () => {
}) })
it('ACOMPUI-15: the marked data fetcher refetches on the next focus', async () => { it('ACOMPUI-15: the marked data fetcher refetches on the next focus', async () => {
setComplaintPages([{ complaints: [COMPLAINT_PENDING] }]) setComplaintPage({ complaints: [COMPLAINT_PENDING] })
renderComplaints() await renderComplaints()
await flush()
expect(trpcMock.__refetch).not.toHaveBeenCalled() // Only the initial fetch so far: the focus hook skips its first pass.
expect(queryCallCount()).toBe(1)
await act(async () => { await act(async () => {
navMock.__triggerFocus() navMock.__triggerFocus()
}) })
await flush() await waitFor(() => expect(queryCallCount()).toBeGreaterThan(1))
expect(trpcMock.__refetch).toHaveBeenCalled()
}) })
it('ACOMPUI-16: pressing an attached image opens the image viewer', async () => { it('ACOMPUI-16: pressing an attached image opens the image viewer', async () => {
setComplaintPages([{ complaints: [COMPLAINT_RESOLVED] }]) setComplaintPage({ complaints: [COMPLAINT_RESOLVED] })
const view = renderComplaints() const view = await renderComplaints()
await flush()
const image = view const image = view
.UNSAFE_getAllByType(Image) .UNSAFE_getAllByType(Image)

View file

@ -4,11 +4,11 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import { MyButton } from 'common-ui' import { MyButton } from 'common-ui'
import EditCoupon from '@/app/(drawer)/dashboard/coupons/edit/[id]' import EditCoupon from '@/app/(drawer)/dashboard/coupons/edit/[id]'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -18,11 +18,11 @@ import {
import { router, __setParams } from '../mocks/expo-router-mock' import { router, __setParams } from '../mocks/expo-router-mock'
import { COUPON_1, COUPON_GLOBAL } from '../fixtures' import { COUPON_1, COUPON_GLOBAL } from '../fixtures'
type View = ReturnType<typeof renderEdit>['view'] type View = Awaited<ReturnType<typeof renderEdit>>['view']
function renderEdit() { async function renderEdit() {
__setParams({ id: '21' }) __setParams({ id: '21' })
const view = renderWithProviders(<EditCoupon />, { auth: false }) const view = await renderAndFlush(<EditCoupon />, { auth: false })
return { view } return { view }
} }
@ -37,7 +37,6 @@ function couponResponse(coupon: any) {
async function submit(view: View) { async function submit(view: View) {
fireEvent.press(view.getByText('Create Coupon')) fireEvent.press(view.getByText('Create Coupon'))
await flush(3)
} }
describe('Coupon edit (ACOUPE-01..10)', () => { describe('Coupon edit (ACOUPE-01..10)', () => {
@ -52,21 +51,22 @@ describe('Coupon edit (ACOUPE-01..10)', () => {
it('ACOUPE-01: shows the loading state', () => { it('ACOUPE-01: shows the loading state', () => {
setProcedure('admin.coupon.getById', { mode: 'pending' }) setProcedure('admin.coupon.getById', { mode: 'pending' })
const { view } = renderEdit() __setParams({ id: '21' })
const view = renderWithProviders(<EditCoupon />, { auth: false })
expect(view.getByText('Loading...')).toBeTruthy() expect(view.getByText('Loading...')).toBeTruthy()
}) })
it('ACOUPE-02: shows Coupon not found when the coupon is missing', () => { it('ACOUPE-02: shows Coupon not found when the coupon is missing', async () => {
setProcedure('admin.coupon.getById', { data: couponResponse(null) }) setProcedure('admin.coupon.getById', { data: couponResponse(null) })
const { view } = renderEdit() const { view } = await renderEdit()
expect(view.getByText('Coupon not found')).toBeTruthy() expect(view.getByText('Coupon not found')).toBeTruthy()
}) })
it('ACOUPE-03: prefills code, discount and product targeting', () => { it('ACOUPE-03: prefills code, discount and product targeting', async () => {
setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) }) setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) })
const { view } = renderEdit() const { view } = await renderEdit()
expect(codeInput(view).props.value).toBe('SAVE10') expect(codeInput(view).props.value).toBe('SAVE10')
expect(view.getByPlaceholderText('e.g., 10').props.value).toBe('10') expect(view.getByPlaceholderText('e.g., 10').props.value).toBe('10')
@ -77,40 +77,48 @@ describe('Coupon edit (ACOUPE-01..10)', () => {
it('ACOUPE-04: saving calls update with { id, updates } and refreshes the list', async () => { it('ACOUPE-04: saving calls update with { id, updates } and refreshes the list', async () => {
setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) }) setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) })
const { view } = renderEdit() const { view } = await renderEdit()
fireEvent.changeText(codeInput(view), 'SAVE20') fireEvent.changeText(codeInput(view), 'SAVE20')
await submit(view) await submit(view)
await waitFor(() =>
expect(lastMutationInput('admin.coupon.update')).toBeTruthy()
)
const input = lastMutationInput('admin.coupon.update') const input = lastMutationInput('admin.coupon.update')
expect(input.id).toBe(21) expect(input.id).toBe(21)
expect(input.updates.couponCodes).toEqual(['SAVE20']) expect(input.updates.couponCodes).toEqual(['SAVE20'])
await waitFor(() =>
expect(procedureInvalidations('admin.coupon.getAll').length).toBeGreaterThan(0) expect(procedureInvalidations('admin.coupon.getAll').length).toBeGreaterThan(0)
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Success', 'Success',
'Coupon updated successfully', 'Coupon updated successfully',
expect.any(Array) expect.any(Array)
) )
)
}) })
it('ACOUPE-05: a failed update shows the server message', async () => { it('ACOUPE-05: a failed update shows the server message', async () => {
setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) }) setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) })
setProcedure('admin.coupon.update', { mode: 'error', error: new Error('Boom') }) setProcedure('admin.coupon.update', { mode: 'error', error: new Error('Boom') })
const { view } = renderEdit() const { view } = await renderEdit()
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Boom') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'Boom'))
}) })
it('ACOUPE-06: flat discounts copy maxValue into the payload', async () => { it('ACOUPE-06: flat discounts copy maxValue into the payload', async () => {
setProcedure('admin.coupon.getById', { setProcedure('admin.coupon.getById', {
data: couponResponse({ ...COUPON_1, discountPercent: null, flatDiscount: '50' }), data: couponResponse({ ...COUPON_1, discountPercent: null, flatDiscount: '50' }),
}) })
const { view } = renderEdit() const { view } = await renderEdit()
expect(view.getByPlaceholderText('e.g., 50').props.value).toBe('50') expect(view.getByPlaceholderText('e.g., 50').props.value).toBe('50')
await submit(view) await submit(view)
await waitFor(() => expect(lastMutationInput('admin.coupon.update')).toBeTruthy())
const updates = lastMutationInput('admin.coupon.update').updates const updates = lastMutationInput('admin.coupon.update').updates
expect(updates.flatDiscount).toBe(50) expect(updates.flatDiscount).toBe(50)
@ -121,12 +129,13 @@ describe('Coupon edit (ACOUPE-01..10)', () => {
setProcedure('admin.coupon.getById', { setProcedure('admin.coupon.getById', {
data: couponResponse({ ...COUPON_1, targetUser: { id: 5 } }), data: couponResponse({ ...COUPON_1, targetUser: { id: 5 } }),
}) })
const { view } = renderEdit() const { view } = await renderEdit()
// The selector renders applicableUsers, so the restored targetUser is not // The selector renders applicableUsers, so the restored targetUser is not
// shown there; the payload still carries it. // shown there; the payload still carries it.
expect(view.getByText('Select users...')).toBeTruthy() expect(view.getByText('Select users...')).toBeTruthy()
await submit(view) await submit(view)
await waitFor(() => expect(lastMutationInput('admin.coupon.update')).toBeTruthy())
const updates = lastMutationInput('admin.coupon.update').updates const updates = lastMutationInput('admin.coupon.update').updates
expect(updates.targetUser).toBe(5) expect(updates.targetUser).toBe(5)
@ -136,20 +145,29 @@ describe('Coupon edit (ACOUPE-01..10)', () => {
it('ACOUPE-08: a pending update shows the loading button', async () => { it('ACOUPE-08: a pending update shows the loading button', async () => {
setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) }) setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) })
setProcedure('admin.coupon.update', { mode: 'pending' }) setProcedure('admin.coupon.update', { mode: 'pending' })
const { view } = renderEdit() const { view } = await renderEdit()
await submit(view) await submit(view)
expect(lastMutationInput('admin.coupon.update')).toBeTruthy() await waitFor(() => expect(lastMutationInput('admin.coupon.update')).toBeTruthy())
await waitFor(() =>
expect(view.UNSAFE_getAllByType(MyButton)[0].props.loading).toBe(true) expect(view.UNSAFE_getAllByType(MyButton)[0].props.loading).toBe(true)
)
}) })
it('ACOUPE-09: OK on the success alert goes back', async () => { it('ACOUPE-09: OK on the success alert goes back', async () => {
setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) }) setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_1) })
const { view } = renderEdit() const { view } = await renderEdit()
await submit(view) await submit(view)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith(
'Success',
'Coupon updated successfully',
expect.any(Array)
)
)
const buttons = alertSpy.mock.calls.find((call) => call[0] === 'Success')[2] const buttons = alertSpy.mock.calls.find((call) => call[0] === 'Success')[2]
act(() => { act(() => {
buttons[0].onPress() buttons[0].onPress()
@ -157,9 +175,9 @@ describe('Coupon edit (ACOUPE-01..10)', () => {
expect(router.back).toHaveBeenCalled() expect(router.back).toHaveBeenCalled()
}) })
it('ACOUPE-10: a global coupon is not guarded on this direct route', () => { it('ACOUPE-10: a global coupon is not guarded on this direct route', async () => {
setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_GLOBAL) }) setProcedure('admin.coupon.getById', { data: couponResponse(COUPON_GLOBAL) })
const { view } = renderEdit() const { view } = await renderEdit()
// The route has no global-coupon guard; it renders the editable form. // The route has no global-coupon guard; it renders the editable form.
expect(codeInput(view).props.value).toBe('GLOBAL10') expect(codeInput(view).props.value).toBe('GLOBAL10')

View file

@ -4,12 +4,12 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, DeviceEventEmitter, FlatList } from 'react-native' import { Alert, DeviceEventEmitter, FlatList } from 'react-native'
import { fireEvent, act } from '@testing-library/react-native' import { fireEvent, act, waitFor } from '@testing-library/react-native'
import { BottomDropdown } from 'common-ui' import { BottomDropdown } from 'common-ui'
import { MaterialCommunityIcons } from '@expo/vector-icons' import { MaterialCommunityIcons } from '@expo/vector-icons'
import Coupons from '@/app/(drawer)/dashboard/coupons/index' import Coupons from '@/app/(drawer)/dashboard/coupons/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -34,24 +34,24 @@ function response(coupons: any[]) {
return { coupons, count: coupons.length, nextCursor: undefined } return { coupons, count: coupons.length, nextCursor: undefined }
} }
function paginated(coupons: any[]) { // Each network response is one infinite-query page; React Query assembles the
return { pages: [response(coupons)], pageParams: [0] } // `pages` array itself.
function page(coupons: any[]) {
return response(coupons)
} }
type View = Awaited<ReturnType<typeof renderCoupons>>
function renderCoupons() { function renderCoupons() {
return renderWithProviders(<Coupons />, { auth: false }) return renderAndFlush(<Coupons />, { auth: false })
} }
async function openReserved(view: ReturnType<typeof renderCoupons>) { async function openReserved(view: View) {
fireEvent.press(view.getByLabelText('Reserved')) fireEvent.press(view.getByLabelText('Reserved'))
await flush(2) await flush(2)
} }
function selectStatusFilter( function selectStatusFilter(view: View, values: string[], index = 0) {
view: ReturnType<typeof renderCoupons>,
values: string[],
index = 0
) {
const dropdowns = view.UNSAFE_getAllByType(BottomDropdown) const dropdowns = view.UNSAFE_getAllByType(BottomDropdown)
const dropdown = dropdowns[index < 0 ? dropdowns.length - 1 : index] const dropdown = dropdowns[index < 0 ? dropdowns.length - 1 : index]
act(() => { act(() => {
@ -69,9 +69,9 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('ACOUPUI-01: renders the General and Reserved tabs', () => { it('ACOUPUI-01: renders the General and Reserved tabs', async () => {
setProcedure('admin.coupon.getAll', { data: paginated(COUPONS) }) setProcedure('admin.coupon.getAll', { data: page(COUPONS) })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getAllByText('General').length).toBeGreaterThan(0) expect(view.getAllByText('General').length).toBeGreaterThan(0)
expect(view.getAllByText('Reserved').length).toBeGreaterThan(0) expect(view.getAllByText('Reserved').length).toBeGreaterThan(0)
@ -80,48 +80,60 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
it('ACOUPUI-02: shows the General loading state', () => { it('ACOUPUI-02: shows the General loading state', () => {
setProcedure('admin.coupon.getAll', { mode: 'pending' }) setProcedure('admin.coupon.getAll', { mode: 'pending' })
const view = renderCoupons() const view = renderWithProviders(<Coupons />, { auth: false })
expect(view.getByText('Loading Coupons...')).toBeTruthy() expect(view.getByText('Loading Coupons...')).toBeTruthy()
}) })
it('ACOUPUI-03: shows the General error state and retries', async () => { it('ACOUPUI-03: shows the General error state and retries', async () => {
setProcedure('admin.coupon.getAll', { mode: 'error', error: new Error('boom') }) setProcedure('admin.coupon.getAll', { mode: 'error', error: new Error('boom') })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getByText('Failed to load coupons')).toBeTruthy() expect(view.getByText('Failed to load coupons')).toBeTruthy()
const calls = procedureQueryCalls('admin.coupon.getAll').length const calls = procedureQueryCalls('admin.coupon.getAll').length
fireEvent.press(view.getByText('Retry')) fireEvent.press(view.getByText('Retry'))
await flush() await waitFor(() =>
expect(procedureQueryCalls('admin.coupon.getAll').length).toBe(calls) expect(procedureQueryCalls('admin.coupon.getAll').length).toBe(calls + 1)
)
expect(view.getByText('Failed to load coupons')).toBeTruthy()
}) })
it('ACOUPUI-04: shows the empty General state', () => { it('ACOUPUI-04: shows the empty General state', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([]) }) setProcedure('admin.coupon.getAll', { data: page([]) })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getByText('No Coupons Found')).toBeTruthy() expect(view.getByText('No Coupons Found')).toBeTruthy()
expect(view.queryByText('Clear Search')).toBeNull() expect(view.queryByText('Clear Search')).toBeNull()
}) })
it('ACOUPUI-05: empty search results reveal Clear Search, which resets the query', async () => { it('ACOUPUI-05: empty search results reveal Clear Search, which resets the query', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([]) }) setProcedure('admin.coupon.getAll', { data: page([]) })
const view = renderCoupons() const view = await renderCoupons()
fireEvent.changeText(view.getByPlaceholderText('Search coupons...'), 'missing') fireEvent.changeText(view.getByPlaceholderText('Search coupons...'), 'missing')
await flush(2) await waitFor(() =>
expect(lastProcedureInput('admin.coupon.getAll')).toEqual({
limit: 20,
search: 'missing',
direction: 'forward',
})
)
expect(view.getByText('No Coupons Found')).toBeTruthy() expect(view.getByText('No Coupons Found')).toBeTruthy()
expect(view.getByText('Clear Search')).toBeTruthy() expect(view.getByText('Clear Search')).toBeTruthy()
fireEvent.press(view.getByText('Clear Search')) fireEvent.press(view.getByText('Clear Search'))
await flush(2) await waitFor(() => expect(view.getByPlaceholderText('Search coupons...').props.value).toBe(''))
expect(view.getByPlaceholderText('Search coupons...').props.value).toBe('') // Clearing returns to the unfiltered query (already cached from the first render).
expect(lastProcedureInput('admin.coupon.getAll')).toEqual({ limit: 20, search: '' }) expect(procedureQueryCalls('admin.coupon.getAll')).toContainEqual({
limit: 20,
search: '',
direction: 'forward',
})
}) })
it('ACOUPUI-06: renders the coupon card fields', () => { it('ACOUPUI-06: renders the coupon card fields', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_1]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getByText('SAVE10')).toBeTruthy() expect(view.getByText('SAVE10')).toBeTruthy()
expect(view.getByText('ID: 21')).toBeTruthy() expect(view.getByText('ID: 21')).toBeTruthy()
@ -133,32 +145,32 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
expect(view.getByText(/Target: All Users/)).toBeTruthy() expect(view.getByText(/Target: All Users/)).toBeTruthy()
}) })
it('ACOUPUI-07: an active coupon shows Active', () => { it('ACOUPUI-07: an active coupon shows Active', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_1]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getByText('Active')).toBeTruthy() expect(view.getByText('Active')).toBeTruthy()
}) })
it('ACOUPUI-08: an expired coupon shows Expired', () => { it('ACOUPUI-08: an expired coupon shows Expired', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_EXPIRED]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_EXPIRED]) })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getByText('Expired')).toBeTruthy() expect(view.getByText('Expired')).toBeTruthy()
expect(view.getByText('OLD')).toBeTruthy() expect(view.getByText('OLD')).toBeTruthy()
}) })
it('ACOUPUI-09: an invalidated coupon shows Inactive', () => { it('ACOUPUI-09: an invalidated coupon shows Inactive', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_INVALIDATED]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_INVALIDATED]) })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getByText('Inactive')).toBeTruthy() expect(view.getByText('Inactive')).toBeTruthy()
expect(view.getByText('DEAD')).toBeTruthy() expect(view.getByText('DEAD')).toBeTruthy()
}) })
it('ACOUPUI-10: a global coupon is read-only and explains why', () => { it('ACOUPUI-10: a global coupon is read-only and explains why', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_GLOBAL]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_GLOBAL]) })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getByText('GLOBAL10')).toBeTruthy() expect(view.getByText('GLOBAL10')).toBeTruthy()
expect(view.getByText('Global')).toBeTruthy() expect(view.getByText('Global')).toBeTruthy()
@ -169,36 +181,36 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
expect(view.queryByText('Delete')).toBeNull() expect(view.queryByText('Delete')).toBeNull()
}) })
it('ACOUPUI-11: shows N Users vs All Users for the target audience', () => { it('ACOUPUI-11: shows N Users vs All Users for the target audience', async () => {
setProcedure('admin.coupon.getAll', { setProcedure('admin.coupon.getAll', {
data: paginated([ data: page([
{ ...COUPON_1, id: 31, couponCode: 'USERS', isApplyForAll: false, applicableUsers: [{ id: 5 }, { id: 6 }] }, { ...COUPON_1, id: 31, couponCode: 'USERS', isApplyForAll: false, applicableUsers: [{ id: 5 }, { id: 6 }] },
]), ]),
}) })
const view = renderCoupons() const view = await renderCoupons()
expect(view.getByText(/Target: 2 Users/)).toBeTruthy() expect(view.getByText(/Target: 2 Users/)).toBeTruthy()
view.unmount() view.unmount()
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_1]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
const allView = renderCoupons() const allView = await renderCoupons()
expect(allView.getByText(/Target: All Users/)).toBeTruthy() expect(allView.getByText(/Target: All Users/)).toBeTruthy()
}) })
it('ACOUPUI-12: hides the Products line when no SKUs are targeted', () => { it('ACOUPUI-12: hides the Products line when no SKUs are targeted', async () => {
const view = renderCoupons() const view = await renderCoupons()
expect(view.queryByText(/Products: \d+ selected/)).toBeNull() expect(view.queryByText(/Products: \d+ selected/)).toBeNull()
const withSkus = { ...COUPON_1, id: 32, couponCode: 'SKU10', skuIds: [11, 12] } const withSkus = { ...COUPON_1, id: 32, couponCode: 'SKU10', skuIds: [11, 12] }
setProcedure('admin.coupon.getAll', { data: paginated([withSkus]) }) setProcedure('admin.coupon.getAll', { data: page([withSkus]) })
view.unmount() view.unmount()
const skuView = renderCoupons() const skuView = await renderCoupons()
expect(skuView.getByText(/Products: 2 selected/)).toBeTruthy() expect(skuView.getByText(/Products: 2 selected/)).toBeTruthy()
}) })
it('ACOUPUI-13: Edit opens the coupon edit route', () => { it('ACOUPUI-13: Edit opens the coupon edit route', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_1]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
const view = renderCoupons() const view = await renderCoupons()
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
@ -206,8 +218,8 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
}) })
it('ACOUPUI-14: Delete asks for confirmation and Cancel makes no API call', async () => { it('ACOUPUI-14: Delete asks for confirmation and Cancel makes no API call', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_1]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
const view = renderCoupons() const view = await renderCoupons()
fireEvent.press(view.getByText('Delete')) fireEvent.press(view.getByText('Delete'))
@ -224,38 +236,38 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
}) })
it('ACOUPUI-15: confirming Delete calls the mutation and reports success', async () => { it('ACOUPUI-15: confirming Delete calls the mutation and reports success', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_1]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
const view = renderCoupons() const view = await renderCoupons()
fireEvent.press(view.getByText('Delete')) fireEvent.press(view.getByText('Delete'))
const buttons = alertSpy.mock.calls[0][2] const buttons = alertSpy.mock.calls[0][2]
await act(async () => { await act(async () => {
await buttons[1].onPress() await buttons[1].onPress()
}) })
await flush(2)
expect(lastMutationInput('admin.coupon.delete')).toEqual({ id: 21 }) await waitFor(() => expect(lastMutationInput('admin.coupon.delete')).toEqual({ id: 21 }))
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Coupon deleted successfully') expect(alertSpy).toHaveBeenCalledWith('Success', 'Coupon deleted successfully')
)
}) })
it('ACOUPUI-16: a failed delete shows an error alert', async () => { it('ACOUPUI-16: a failed delete shows an error alert', async () => {
setProcedure('admin.coupon.getAll', { data: paginated([COUPON_1]) }) setProcedure('admin.coupon.getAll', { data: page([COUPON_1]) })
setProcedure('admin.coupon.delete', { mode: 'error', error: new Error('nope') }) setProcedure('admin.coupon.delete', { mode: 'error', error: new Error('nope') })
const view = renderCoupons() const view = await renderCoupons()
fireEvent.press(view.getByText('Delete')) fireEvent.press(view.getByText('Delete'))
const buttons = alertSpy.mock.calls[0][2] const buttons = alertSpy.mock.calls[0][2]
await act(async () => { await act(async () => {
await buttons[1].onPress() await buttons[1].onPress()
}) })
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'nope') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope'))
}) })
it('ACOUPUI-17: the status filter narrows the list to active/expired/inactive', () => { it('ACOUPUI-17: the status filter narrows the list to active/expired/inactive', async () => {
setProcedure('admin.coupon.getAll', { data: paginated(COUPONS) }) setProcedure('admin.coupon.getAll', { data: page(COUPONS) })
const view = renderCoupons() const view = await renderCoupons()
selectStatusFilter(view, ['active']) selectStatusFilter(view, ['active'])
expect(view.queryByText('OLD')).toBeNull() expect(view.queryByText('OLD')).toBeNull()
@ -272,17 +284,22 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
}) })
it('ACOUPUI-18: typing a search sends the query to the API', async () => { it('ACOUPUI-18: typing a search sends the query to the API', async () => {
const view = renderCoupons() const view = await renderCoupons()
fireEvent.changeText(view.getByPlaceholderText('Search coupons...'), 'SAVE') fireEvent.changeText(view.getByPlaceholderText('Search coupons...'), 'SAVE')
await flush(2)
expect(lastProcedureInput('admin.coupon.getAll')).toEqual({ limit: 20, search: 'SAVE' }) await waitFor(() =>
expect(lastProcedureInput('admin.coupon.getAll')).toEqual({
limit: 20,
search: 'SAVE',
direction: 'forward',
})
)
}) })
it('ACOUPUI-19: reaching the end never duplicates rows', async () => { it('ACOUPUI-19: reaching the end never duplicates rows', async () => {
setProcedure('admin.coupon.getAll', { data: paginated(COUPONS) }) setProcedure('admin.coupon.getAll', { data: page(COUPONS) })
const view = renderCoupons() const view = await renderCoupons()
const list = view.UNSAFE_getAllByType(FlatList)[0] const list = view.UNSAFE_getAllByType(FlatList)[0]
await act(async () => { await act(async () => {
@ -296,20 +313,23 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
}) })
it('ACOUPUI-20: a manual refresh keeps the list rendered', async () => { it('ACOUPUI-20: a manual refresh keeps the list rendered', async () => {
setProcedure('admin.coupon.getAll', { data: paginated(COUPONS) }) setProcedure('admin.coupon.getAll', { data: page(COUPONS) })
const view = renderCoupons() const view = await renderCoupons()
const calls = procedureQueryCalls('admin.coupon.getAll').length
await act(async () => { await act(async () => {
DeviceEventEmitter.emit('refresh_event') DeviceEventEmitter.emit('refresh_event')
}) })
await flush()
await waitFor(() =>
expect(procedureQueryCalls('admin.coupon.getAll').length).toBeGreaterThan(calls)
)
expect(view.getByText('SAVE10')).toBeTruthy() expect(view.getByText('SAVE10')).toBeTruthy()
expect(view.queryByText('Failed to load coupons')).toBeNull() expect(view.queryByText('Failed to load coupons')).toBeNull()
}) })
it('ACOUPUI-21: the Add FAB opens the create route', () => { it('ACOUPUI-21: the Add FAB opens the create route', async () => {
const view = renderCoupons() const view = await renderCoupons()
const icon = view const icon = view
.UNSAFE_getAllByType(MaterialCommunityIcons) .UNSAFE_getAllByType(MaterialCommunityIcons)
@ -321,7 +341,7 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
it('ACOUPUI-22: shows the Reserved loading state', async () => { it('ACOUPUI-22: shows the Reserved loading state', async () => {
setProcedure('admin.coupon.getReservedCoupons', { mode: 'pending' }) setProcedure('admin.coupon.getReservedCoupons', { mode: 'pending' })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
@ -330,7 +350,7 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
it('ACOUPUI-23: shows the Reserved error state and retries', async () => { it('ACOUPUI-23: shows the Reserved error state and retries', async () => {
setProcedure('admin.coupon.getReservedCoupons', { mode: 'error', error: new Error('boom') }) setProcedure('admin.coupon.getReservedCoupons', { mode: 'error', error: new Error('boom') })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
@ -341,17 +361,17 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
}) })
it('ACOUPUI-24: shows the empty Reserved state', async () => { it('ACOUPUI-24: shows the empty Reserved state', async () => {
setProcedure('admin.coupon.getReservedCoupons', { data: paginated([]) }) setProcedure('admin.coupon.getReservedCoupons', { data: page([]) })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
expect(view.getByText('No Reserved Coupons Found')).toBeTruthy() expect(await view.findByText('No Reserved Coupons Found')).toBeTruthy()
}) })
it('ACOUPUI-25: renders the reserved coupon card fields', async () => { it('ACOUPUI-25: renders the reserved coupon card fields', async () => {
setProcedure('admin.coupon.getReservedCoupons', { setProcedure('admin.coupon.getReservedCoupons', {
data: paginated([ data: page([
{ {
...COUPON_1, ...COUPON_1,
id: 25, id: 25,
@ -362,11 +382,11 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
}, },
]), ]),
}) })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
expect(view.getByText('SECRET123')).toBeTruthy() expect(await view.findByText('SECRET123')).toBeTruthy()
expect(view.getByText('Coupon: RES10')).toBeTruthy() expect(view.getByText('Coupon: RES10')).toBeTruthy()
expect(view.getByText('Active')).toBeTruthy() expect(view.getByText('Active')).toBeTruthy()
expect(view.getByText('Discount: 10% off')).toBeTruthy() expect(view.getByText('Discount: 10% off')).toBeTruthy()
@ -376,7 +396,7 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
it('ACOUPUI-26: reserved active/expired/redeemed statuses render', async () => { it('ACOUPUI-26: reserved active/expired/redeemed statuses render', async () => {
setProcedure('admin.coupon.getReservedCoupons', { setProcedure('admin.coupon.getReservedCoupons', {
data: paginated([ data: page([
{ ...COUPON_1, id: 41, couponCode: 'ACT', secretCode: 'ACTIVE1', isRedeemed: false, creator: { name: 'Admin One' } }, { ...COUPON_1, id: 41, couponCode: 'ACT', secretCode: 'ACTIVE1', isRedeemed: false, creator: { name: 'Admin One' } },
{ {
...COUPON_1, ...COUPON_1,
@ -390,11 +410,11 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
{ ...COUPON_1, id: 43, couponCode: 'RED', secretCode: 'REDEEMED1', isRedeemed: true, creator: { name: 'Admin One' } }, { ...COUPON_1, id: 43, couponCode: 'RED', secretCode: 'REDEEMED1', isRedeemed: true, creator: { name: 'Admin One' } },
]), ]),
}) })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
expect(view.getByText('ACTIVE1')).toBeTruthy() expect(await view.findByText('ACTIVE1')).toBeTruthy()
expect(view.getByText('EXPIRED1')).toBeTruthy() expect(view.getByText('EXPIRED1')).toBeTruthy()
expect(view.getByText('REDEEMED1')).toBeTruthy() expect(view.getByText('REDEEMED1')).toBeTruthy()
expect(view.getByText('Expired')).toBeTruthy() expect(view.getByText('Expired')).toBeTruthy()
@ -403,7 +423,7 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
it('ACOUPUI-27: a redeemed coupon shows who redeemed it and when', async () => { it('ACOUPUI-27: a redeemed coupon shows who redeemed it and when', async () => {
setProcedure('admin.coupon.getReservedCoupons', { setProcedure('admin.coupon.getReservedCoupons', {
data: paginated([ data: page([
{ {
...COUPON_1, ...COUPON_1,
id: 44, id: 44,
@ -416,30 +436,30 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
}, },
]), ]),
}) })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
expect(view.getByText(/Redeemed by: Test User \(9876543210\)/)).toBeTruthy() expect(await view.findByText(/Redeemed by: Test User \(9876543210\)/)).toBeTruthy()
expect(view.getByText(/Redeemed on:/)).toBeTruthy() expect(view.getByText(/Redeemed on:/)).toBeTruthy()
}) })
it('ACOUPUI-28: a reserved coupon shows its creator', async () => { it('ACOUPUI-28: a reserved coupon shows its creator', async () => {
setProcedure('admin.coupon.getReservedCoupons', { setProcedure('admin.coupon.getReservedCoupons', {
data: paginated([ data: page([
{ ...COUPON_1, id: 45, couponCode: 'CRE', secretCode: 'CREATOR1', creator: { name: 'Admin Two' } }, { ...COUPON_1, id: 45, couponCode: 'CRE', secretCode: 'CREATOR1', creator: { name: 'Admin Two' } },
]), ]),
}) })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
expect(view.getByText(/Created by: Admin Two/)).toBeTruthy() expect(await view.findByText(/Created by: Admin Two/)).toBeTruthy()
}) })
it('ACOUPUI-29: the reserved status filter narrows the list', async () => { it('ACOUPUI-29: the reserved status filter narrows the list', async () => {
setProcedure('admin.coupon.getReservedCoupons', { setProcedure('admin.coupon.getReservedCoupons', {
data: paginated([ data: page([
{ ...COUPON_1, id: 51, couponCode: 'A', secretCode: 'ACTIVE9', isRedeemed: false, creator: { name: 'Admin One' } }, { ...COUPON_1, id: 51, couponCode: 'A', secretCode: 'ACTIVE9', isRedeemed: false, creator: { name: 'Admin One' } },
{ {
...COUPON_1, ...COUPON_1,
@ -453,9 +473,10 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
{ ...COUPON_1, id: 53, couponCode: 'R', secretCode: 'RED9', isRedeemed: true, creator: { name: 'Admin One' } }, { ...COUPON_1, id: 53, couponCode: 'R', secretCode: 'RED9', isRedeemed: true, creator: { name: 'Admin One' } },
]), ]),
}) })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
expect(await view.findByText('ACTIVE9')).toBeTruthy()
selectStatusFilter(view, ['redeemed'], -1) selectStatusFilter(view, ['redeemed'], -1)
expect(view.getByText('RED9')).toBeTruthy() expect(view.getByText('RED9')).toBeTruthy()
@ -469,17 +490,23 @@ describe('Coupons list (ACOUPUI-01..30)', () => {
it('ACOUPUI-30: reserved search/filter/refresh keeps the list consistent', async () => { it('ACOUPUI-30: reserved search/filter/refresh keeps the list consistent', async () => {
setProcedure('admin.coupon.getReservedCoupons', { setProcedure('admin.coupon.getReservedCoupons', {
data: paginated([ data: page([
{ ...COUPON_1, id: 61, couponCode: 'SEARCH', secretCode: 'SEARCH1', creator: { name: 'Admin One' } }, { ...COUPON_1, id: 61, couponCode: 'SEARCH', secretCode: 'SEARCH1', creator: { name: 'Admin One' } },
]), ]),
}) })
const view = renderCoupons() const view = await renderCoupons()
await openReserved(view) await openReserved(view)
expect(await view.findByText('SEARCH1')).toBeTruthy()
fireEvent.changeText(view.getByPlaceholderText('Search reserved coupons...'), 'SEARCH') fireEvent.changeText(view.getByPlaceholderText('Search reserved coupons...'), 'SEARCH')
await flush(2) await waitFor(() =>
expect(lastProcedureInput('admin.coupon.getReservedCoupons')).toEqual({ limit: 20, search: 'SEARCH' }) expect(lastProcedureInput('admin.coupon.getReservedCoupons')).toEqual({
limit: 20,
search: 'SEARCH',
direction: 'forward',
})
)
selectStatusFilter(view, ['active'], -1) selectStatusFilter(view, ['active'], -1)
expect(view.getByText('SEARCH1')).toBeTruthy() expect(view.getByText('SEARCH1')).toBeTruthy()

View file

@ -5,10 +5,10 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import CustomizeApp from '@/app/(drawer)/dashboard/customize-app/index' import CustomizeApp from '@/app/(drawer)/dashboard/customize-app/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, flush, createTestQueryClient } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
@ -55,10 +55,15 @@ describe('Customize app (ACUST-01..26)', () => {
it('ACUST-01: shows the bounds loading state', async () => { it('ACUST-01: shows the bounds loading state', async () => {
setProcedure('admin.region.bounds', { mode: 'pending' }) setProcedure('admin.region.bounds', { mode: 'pending' })
const view = await renderPage() // The real batch link puts every mount-time query in one request, so a
// pending bounds response would hold `region.current` too. Seed the header
// (as an earlier screen would have) and keep only the bounds query in flight.
const queryClient = createTestQueryClient()
queryClient.setQueryData([['admin', 'region', 'current'], { type: 'query' }], REGION)
const view = renderWithProviders(<CustomizeApp />, { auth: false, queryClient })
expect(await view.findByText('Region: Mahabubnagar')).toBeTruthy()
expect(view.getByText('Customize App')).toBeTruthy() expect(view.getByText('Customize App')).toBeTruthy()
expect(view.getByText('Region: Mahabubnagar')).toBeTruthy()
expect(view.getByText('Loading bounds...')).toBeTruthy() expect(view.getByText('Loading bounds...')).toBeTruthy()
}) })
@ -66,7 +71,7 @@ describe('Customize app (ACUST-01..26)', () => {
setProcedure('admin.region.bounds', { mode: 'error', error: new Error('bounds boom') }) setProcedure('admin.region.bounds', { mode: 'error', error: new Error('bounds boom') })
const view = await renderPage() const view = await renderPage()
expect(view.getByText('Failed to load bounds')).toBeTruthy() expect(await view.findByText('Failed to load bounds')).toBeTruthy()
expect(view.getByText('bounds boom')).toBeTruthy() expect(view.getByText('bounds boom')).toBeTruthy()
fireEvent.press(view.getByText('Retry')) fireEvent.press(view.getByText('Retry'))
@ -79,7 +84,7 @@ describe('Customize app (ACUST-01..26)', () => {
setProcedure('admin.region.bounds', { data: [] }) setProcedure('admin.region.bounds', { data: [] })
const view = await renderPage() const view = await renderPage()
expect(view.getByText('No bounds configured')).toBeTruthy() expect(await view.findByText('No bounds configured')).toBeTruthy()
expect( expect(
view.getByText('This region has no bounds yet. Ask a superadmin to configure one.') view.getByText('This region has no bounds yet. Ask a superadmin to configure one.')
).toBeTruthy() ).toBeTruthy()
@ -88,7 +93,7 @@ describe('Customize app (ACUST-01..26)', () => {
it('ACUST-04: lists bounds with priority, current and effective labels', async () => { it('ACUST-04: lists bounds with priority, current and effective labels', async () => {
const view = await renderPage() const view = await renderPage()
expect(view.getByText('Bound #7')).toBeTruthy() expect(await view.findByText('Bound #7')).toBeTruthy()
expect(view.getByText('Bound #8')).toBeTruthy() expect(view.getByText('Bound #8')).toBeTruthy()
expect(view.getByText('Priority 1')).toBeTruthy() expect(view.getByText('Priority 1')).toBeTruthy()
expect(view.getByText('Priority 10')).toBeTruthy() expect(view.getByText('Priority 10')).toBeTruthy()
@ -99,36 +104,40 @@ describe('Customize app (ACUST-01..26)', () => {
it('ACUST-05: the lowest-priority bound is selected by default', async () => { it('ACUST-05: the lowest-priority bound is selected by default', async () => {
const view = await renderPage() const view = await renderPage()
expect(view.getByText(/Editing Bound #7/)).toBeTruthy() expect(await view.findByText(/Editing Bound #7/)).toBeTruthy()
await waitFor(() =>
expect(lastProcedureInput('admin.region.getBoundSettings')).toEqual({ boundId: 7 }) expect(lastProcedureInput('admin.region.getBoundSettings')).toEqual({ boundId: 7 })
)
// Switching to the other bound re-queries its settings and moves the editor. // Switching to the other bound re-queries its settings and moves the editor.
fireEvent.press(view.getByText('Bound #8')) fireEvent.press(view.getByText('Bound #8'))
await flush()
expect(view.getByText('Editing Bound #8')).toBeTruthy() expect(await view.findByText('Editing Bound #8')).toBeTruthy()
await waitFor(() =>
expect(lastProcedureInput('admin.region.getBoundSettings')).toEqual({ boundId: 8 }) expect(lastProcedureInput('admin.region.getBoundSettings')).toEqual({ boundId: 8 })
)
}) })
it('ACUST-06: the Bound/Region tabs switch the visible sections', async () => { it('ACUST-06: the Bound/Region tabs switch the visible sections', async () => {
const view = await renderPage() const view = await renderPage()
expect(view.getByText('Free Delivery Threshold')).toBeTruthy() expect(await view.findByText('Free Delivery Threshold')).toBeTruthy()
await openRegionTab(view) await openRegionTab(view)
expect(view.getByText('Region settings apply to every bound in this region.')).toBeTruthy() expect(
await view.findByText('Region settings apply to every bound in this region.')
).toBeTruthy()
expect(view.queryByText('Free Delivery Threshold')).toBeNull() expect(view.queryByText('Free Delivery Threshold')).toBeNull()
fireEvent.press(view.getByText('Bound')) fireEvent.press(view.getByText('Bound'))
await flush() expect(await view.findByText('Free Delivery Threshold')).toBeTruthy()
expect(view.getByText('Free Delivery Threshold')).toBeTruthy()
expect(view.queryByText('Region settings apply to every bound in this region.')).toBeNull() expect(view.queryByText('Region settings apply to every bound in this region.')).toBeNull()
}) })
it('ACUST-07: the bound form shows threshold/charge/flash fields', async () => { it('ACUST-07: the bound form shows threshold/charge/flash fields', async () => {
const view = await renderPage() const view = await renderPage()
expect(view.getByText('Free Delivery Threshold')).toBeTruthy() expect(await view.findByText('Free Delivery Threshold')).toBeTruthy()
expect(view.getByText('Delivery Charge')).toBeTruthy() expect(view.getByText('Delivery Charge')).toBeTruthy()
expect(view.getByText('Flash Free Delivery Threshold')).toBeTruthy() expect(view.getByText('Flash Free Delivery Threshold')).toBeTruthy()
expect(view.getByText('Flash Delivery Charge')).toBeTruthy() expect(view.getByText('Flash Delivery Charge')).toBeTruthy()
@ -143,7 +152,7 @@ describe('Customize app (ACUST-01..26)', () => {
it('ACUST-08: the flash-delivery boolean renders Enabled/Disabled', async () => { it('ACUST-08: the flash-delivery boolean renders Enabled/Disabled', async () => {
const view = await renderPage() const view = await renderPage()
expect(view.getByText('Enabled')).toBeTruthy() expect(await view.findByText('Enabled')).toBeTruthy()
fireEvent.press(view.getByRole('checkbox')) fireEvent.press(view.getByRole('checkbox'))
expect(view.getByText('Disabled')).toBeTruthy() expect(view.getByText('Disabled')).toBeTruthy()
@ -154,17 +163,17 @@ describe('Customize app (ACUST-01..26)', () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = await renderPage() const view = await renderPage()
fireEvent.changeText(view.getByDisplayValue('15'), '20') fireEvent.changeText(await view.findByDisplayValue('15'), '20')
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
await waitFor(() =>
expect(lastMutationInput('admin.region.updateBoundSettings')).toEqual({ expect(lastMutationInput('admin.region.updateBoundSettings')).toEqual({
boundId: 7, boundId: 7,
settings: [{ key: 'deliveryCharge', value: '20' }], settings: [{ key: 'deliveryCharge', value: '20' }],
}) })
expect(alertSpy).toHaveBeenCalledWith( )
'Success', await waitFor(() =>
expect.stringContaining('settings successfully') expect(alertSpy).toHaveBeenCalledWith('Success', expect.stringContaining('settings successfully'))
) )
}) })
@ -172,10 +181,8 @@ describe('Customize app (ACUST-01..26)', () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = await renderPage() const view = await renderPage()
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(await view.findByText('Save Changes'))
await flush() await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('No Changes', 'No settings were modified.'))
expect(alertSpy).toHaveBeenCalledWith('No Changes', 'No settings were modified.')
expect(procedureMutationCalls('admin.region.updateBoundSettings')).toHaveLength(0) expect(procedureMutationCalls('admin.region.updateBoundSettings')).toHaveLength(0)
}) })
@ -188,21 +195,22 @@ describe('Customize app (ACUST-01..26)', () => {
}) })
const view = await renderPage() const view = await renderPage()
fireEvent.changeText(view.getByDisplayValue('15'), '20') fireEvent.changeText(await view.findByDisplayValue('15'), '20')
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Error', 'Error',
'Failed to update settings. Please try again.' 'Failed to update settings. Please try again.'
) )
)
}) })
it('ACUST-12: empty/invalid numbers are parsed as 0', async () => { it('ACUST-12: empty/invalid numbers are parsed as 0', async () => {
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = await renderPage() const view = await renderPage()
const threshold = view.getByDisplayValue('249') const threshold = await view.findByDisplayValue('249')
fireEvent.changeText(threshold, '') fireEvent.changeText(threshold, '')
expect(view.getByDisplayValue('0')).toBeTruthy() expect(view.getByDisplayValue('0')).toBeTruthy()
@ -210,12 +218,13 @@ describe('Customize app (ACUST-01..26)', () => {
expect(view.getByDisplayValue('0')).toBeTruthy() expect(view.getByDisplayValue('0')).toBeTruthy()
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
await waitFor(() =>
expect(lastMutationInput('admin.region.updateBoundSettings')).toEqual({ expect(lastMutationInput('admin.region.updateBoundSettings')).toEqual({
boundId: 7, boundId: 7,
settings: [{ key: 'freeDeliveryThreshold', value: '0' }], settings: [{ key: 'freeDeliveryThreshold', value: '0' }],
}) })
)
}) })
it('ACUST-13: region arrays are parsed from the comma-separated stored values', async () => { it('ACUST-13: region arrays are parsed from the comma-separated stored values', async () => {
@ -223,7 +232,7 @@ describe('Customize app (ACUST-01..26)', () => {
await openRegionTab(view) await openRegionTab(view)
// REGION_CONSTANTS stores '[2,5]' / '[2,5,7]'; parseConstValue splits on commas. // REGION_CONSTANTS stores '[2,5]' / '[2,5,7]'; parseConstValue splits on commas.
expect(view.getByText('Manage Popular Items (2 items)')).toBeTruthy() expect(await view.findByText('Manage Popular Items (2 items)')).toBeTruthy()
expect(view.getByText('Manage All Visible Items (3 items)')).toBeTruthy() expect(view.getByText('Manage All Visible Items (3 items)')).toBeTruthy()
}) })
@ -231,7 +240,7 @@ describe('Customize app (ACUST-01..26)', () => {
const view = await renderPage() const view = await renderPage()
await openRegionTab(view) await openRegionTab(view)
expect(view.getByText('Manage Popular Items (2 items)')).toBeTruthy() expect(await view.findByText('Manage Popular Items (2 items)')).toBeTruthy()
expect(view.getByText('Manage All Visible Items (3 items)')).toBeTruthy() expect(view.getByText('Manage All Visible Items (3 items)')).toBeTruthy()
expect(view.getByText('Support Mobile')).toBeTruthy() expect(view.getByText('Support Mobile')).toBeTruthy()
expect(view.getByDisplayValue('8688182552')).toBeTruthy() expect(view.getByDisplayValue('8688182552')).toBeTruthy()
@ -245,7 +254,7 @@ describe('Customize app (ACUST-01..26)', () => {
const view = await renderPage() const view = await renderPage()
await openRegionTab(view) await openRegionTab(view)
fireEvent.press(view.getByText('Manage Popular Items (2 items)')) fireEvent.press(await view.findByText('Manage Popular Items (2 items)'))
expect(router.push).toHaveBeenCalledWith( expect(router.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/customize-app/popular-items' '/(drawer)/dashboard/customize-app/popular-items'
@ -256,7 +265,7 @@ describe('Customize app (ACUST-01..26)', () => {
const view = await renderPage() const view = await renderPage()
await openRegionTab(view) await openRegionTab(view)
fireEvent.press(view.getByText('Manage All Visible Items (3 items)')) fireEvent.press(await view.findByText('Manage All Visible Items (3 items)'))
expect(router.push).toHaveBeenCalledWith( expect(router.push).toHaveBeenCalledWith(
'/(drawer)/dashboard/customize-app/all-items-order' '/(drawer)/dashboard/customize-app/all-items-order'
@ -268,17 +277,20 @@ describe('Customize app (ACUST-01..26)', () => {
const view = await renderPage() const view = await renderPage()
await openRegionTab(view) await openRegionTab(view)
fireEvent.changeText(view.getByDisplayValue('8688182552'), '9999999999') fireEvent.changeText(await view.findByDisplayValue('8688182552'), '9999999999')
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
await waitFor(() =>
expect(lastMutationInput('admin.region.updateRegionConstants')).toEqual({ expect(lastMutationInput('admin.region.updateRegionConstants')).toEqual({
constants: [{ key: 'supportMobile', value: '9999999999' }], constants: [{ key: 'supportMobile', value: '9999999999' }],
}) })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Success', 'Success',
expect.stringContaining('region settings successfully') expect.stringContaining('region settings successfully')
) )
)
}) })
it('ACUST-18: saving without region edits alerts and skips the API', async () => { it('ACUST-18: saving without region edits alerts and skips the API', async () => {
@ -286,10 +298,10 @@ describe('Customize app (ACUST-01..26)', () => {
const view = await renderPage() const view = await renderPage()
await openRegionTab(view) await openRegionTab(view)
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(await view.findByText('Save Changes'))
await flush() await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('No Changes', 'No region settings were modified.') expect(alertSpy).toHaveBeenCalledWith('No Changes', 'No region settings were modified.')
)
expect(procedureMutationCalls('admin.region.updateRegionConstants')).toHaveLength(0) expect(procedureMutationCalls('admin.region.updateRegionConstants')).toHaveLength(0)
}) })
@ -303,21 +315,22 @@ describe('Customize app (ACUST-01..26)', () => {
const view = await renderPage() const view = await renderPage()
await openRegionTab(view) await openRegionTab(view)
fireEvent.changeText(view.getByDisplayValue('8688182552'), '9999999999') fireEvent.changeText(await view.findByDisplayValue('8688182552'), '9999999999')
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Error', 'Error',
'Failed to update region settings. Please try again.' 'Failed to update region settings. Please try again.'
) )
)
}) })
it('ACUST-20: missing bound settings fall back to numeric 0 / Disabled defaults', async () => { it('ACUST-20: missing bound settings fall back to numeric 0 / Disabled defaults', async () => {
setProcedure('admin.region.getBoundSettings', { data: null }) setProcedure('admin.region.getBoundSettings', { data: null })
const view = await renderPage() const view = await renderPage()
expect(view.getAllByDisplayValue('0')).toHaveLength(4) await waitFor(() => expect(view.getAllByDisplayValue('0')).toHaveLength(4))
expect(view.getByText('Disabled')).toBeTruthy() expect(view.getByText('Disabled')).toBeTruthy()
}) })
@ -326,22 +339,25 @@ describe('Customize app (ACUST-01..26)', () => {
setProcedure('admin.region.updateBoundSettings', { data: { success: true, updatedCount: 1 } }) setProcedure('admin.region.updateBoundSettings', { data: { success: true, updatedCount: 1 } })
const view = await renderPage() const view = await renderPage()
fireEvent.changeText(view.getByDisplayValue('15'), '20') fireEvent.changeText(await view.findByDisplayValue('15'), '20')
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
await waitFor(() =>
expect(lastMutationInput('admin.region.updateBoundSettings')).toEqual({ expect(lastMutationInput('admin.region.updateBoundSettings')).toEqual({
boundId: 7, boundId: 7,
settings: [{ key: 'deliveryCharge', value: '20' }], settings: [{ key: 'deliveryCharge', value: '20' }],
}) })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Updated 1 settings successfully.') expect(alertSpy).toHaveBeenCalledWith('Success', 'Updated 1 settings successfully.')
)
}) })
it('ACUST-22: shows the settings loading state while the bound is unknown', async () => { it('ACUST-22: shows the settings loading state while the bound is unknown', async () => {
setProcedure('admin.region.getBoundSettings', { mode: 'pending' }) setProcedure('admin.region.getBoundSettings', { mode: 'pending' })
const view = await renderPage() const view = await renderPage()
expect(view.getByText('Loading settings...')).toBeTruthy() expect(await view.findByText('Loading settings...')).toBeTruthy()
expect(view.getByText(/Editing Bound #7/)).toBeTruthy() expect(view.getByText(/Editing Bound #7/)).toBeTruthy()
}) })
@ -352,7 +368,7 @@ describe('Customize app (ACUST-01..26)', () => {
}) })
const view = await renderPage() const view = await renderPage()
expect(view.getByText('Failed to load settings')).toBeTruthy() expect(await view.findByText('Failed to load settings')).toBeTruthy()
expect(view.getByText('settings boom')).toBeTruthy() expect(view.getByText('settings boom')).toBeTruthy()
fireEvent.press(view.getByText('Retry')) fireEvent.press(view.getByText('Retry'))
await flush() await flush()
@ -364,30 +380,31 @@ describe('Customize app (ACUST-01..26)', () => {
const view = await renderPage() const view = await renderPage()
await openRegionTab(view) await openRegionTab(view)
expect(view.getByText('Loading region settings...')).toBeTruthy() expect(await view.findByText('Loading region settings...')).toBeTruthy()
}) })
it('ACUST-25: the flash toggle serializes "true"/"false"', async () => { it('ACUST-25: the flash toggle serializes "true"/"false"', async () => {
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = await renderPage() const view = await renderPage()
fireEvent.press(view.getByRole('checkbox')) fireEvent.press(await view.findByRole('checkbox'))
expect(view.getByText('Disabled')).toBeTruthy() expect(view.getByText('Disabled')).toBeTruthy()
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
// Flip the stored value so the inverse toggle is also a real change. // Flip the stored value so the inverse toggle is also a real change.
setProcedure('admin.region.getBoundSettings', { setProcedure('admin.region.getBoundSettings', {
data: { ...BOUND_SETTINGS, isFlashDeliveryEnabled: 'false' }, data: { ...BOUND_SETTINGS, isFlashDeliveryEnabled: 'false' },
}) })
await flush() await waitFor(() => expect(view.getByText('Disabled')).toBeTruthy())
expect(view.getByText('Disabled')).toBeTruthy() await waitFor(() =>
expect(procedureMutationCalls('admin.region.updateBoundSettings')).toHaveLength(1)
)
fireEvent.press(view.getByRole('checkbox')) fireEvent.press(view.getByRole('checkbox'))
expect(view.getByText('Enabled')).toBeTruthy() expect(view.getByText('Enabled')).toBeTruthy()
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
await waitFor(() =>
expect( expect(
procedureMutationCalls('admin.region.updateBoundSettings').map( procedureMutationCalls('admin.region.updateBoundSettings').map(
(input: any) => input.settings (input: any) => input.settings
@ -396,6 +413,7 @@ describe('Customize app (ACUST-01..26)', () => {
[{ key: 'isFlashDeliveryEnabled', value: 'false' }], [{ key: 'isFlashDeliveryEnabled', value: 'false' }],
[{ key: 'isFlashDeliveryEnabled', value: 'true' }], [{ key: 'isFlashDeliveryEnabled', value: 'true' }],
]) ])
)
}) })
it('ACUST-26: a multiline welcome message is preserved verbatim', async () => { it('ACUST-26: a multiline welcome message is preserved verbatim', async () => {
@ -403,12 +421,13 @@ describe('Customize app (ACUST-01..26)', () => {
const view = await renderPage() const view = await renderPage()
await openRegionTab(view) await openRegionTab(view)
fireEvent.changeText(view.getByDisplayValue('Welcome'), 'Line one\nLine two') fireEvent.changeText(await view.findByDisplayValue('Welcome'), 'Line one\nLine two')
fireEvent.press(view.getByText('Save Changes')) fireEvent.press(view.getByText('Save Changes'))
await flush()
await waitFor(() =>
expect(lastMutationInput('admin.region.updateRegionConstants')).toEqual({ expect(lastMutationInput('admin.region.updateRegionConstants')).toEqual({
constants: [{ key: 'welcomeMessage', value: 'Line one\nLine two' }], constants: [{ key: 'welcomeMessage', value: 'Line one\nLine two' }],
}) })
)
}) })
}) })

View file

@ -56,16 +56,17 @@ describe('Dashboard hub (ADASH-01..15)', () => {
expect(view.getByText('Send Notifications')).toBeTruthy() expect(view.getByText('Send Notifications')).toBeTruthy()
}) })
it('ADASH-02: shows the unresolved-complaint badge count from essentials', () => { it('ADASH-02: shows the unresolved-complaint badge count from essentials', async () => {
setProcedure('admin.user.getEssentials', { data: { unresolvedComplaints: 7 } }) setProcedure('admin.user.getEssentials', { data: { unresolvedComplaints: 7 } })
const view = renderDashboard() const view = renderDashboard()
expect(view.getByText('7')).toBeTruthy() expect(await view.findByText('7')).toBeTruthy()
}) })
it('ADASH-03: no badge when there are zero unresolved complaints', () => { it('ADASH-03: no badge when there are zero unresolved complaints', async () => {
setProcedure('admin.user.getEssentials', { data: { unresolvedComplaints: 0 } }) setProcedure('admin.user.getEssentials', { data: { unresolvedComplaints: 0 } })
const view = renderDashboard() const view = renderDashboard()
await flush()
expect(view.queryByText('0')).toBeNull() expect(view.queryByText('0')).toBeNull()
}) })

View file

@ -5,7 +5,7 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, DeviceEventEmitter } from 'react-native' import { Alert, DeviceEventEmitter } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import DraggableFlatList from 'react-native-draggable-flatlist' import DraggableFlatList from 'react-native-draggable-flatlist'
jest.mock('expo-location', () => ({ jest.mock('expo-location', () => ({
@ -17,7 +17,12 @@ jest.mock('expo-location', () => ({
})) }))
import DeliverySequences from '@/app/(drawer)/dashboard/manage-orders/delivery-sequences/index' import DeliverySequences from '@/app/(drawer)/dashboard/manage-orders/delivery-sequences/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import {
createTestQueryClient,
renderWithProviders,
renderAndFlush,
flush,
} from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
@ -26,7 +31,7 @@ import {
setProcedure, setProcedure,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { router, __setParams } from '../mocks/expo-router-mock' import { router, __setParams } from '../mocks/expo-router-mock'
import { SLOT_ORDERS } from '../fixtures' import { SLOTS, SLOT_ORDERS } from '../fixtures'
const SLOT_ID = '1849' const SLOT_ID = '1849'
@ -48,32 +53,49 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
/** Render and let the slots/orders/sequence queries resolve. */
function renderSequences(params: Record<string, string> = { slotId: SLOT_ID }) { function renderSequences(params: Record<string, string> = { slotId: SLOT_ID }) {
__setParams(params) __setParams(params)
return renderWithProviders(<DeliverySequences />, { auth: 'in' }) return renderAndFlush(<DeliverySequences />, { auth: 'in' })
} }
function selectUser(view: ReturnType<typeof renderSequences>, userId: string) { function selectUser(
view: Awaited<ReturnType<typeof renderSequences>>,
userId: string
) {
fireEvent.press(view.getByTestId('delivery-sequence-user-dropdown')) fireEvent.press(view.getByTestId('delivery-sequence-user-dropdown'))
fireEvent.press(view.getByTestId(`delivery-sequence-user-dropdown-option-${userId}`)) fireEvent.press(view.getByTestId(`delivery-sequence-user-dropdown-option-${userId}`))
} }
/** Drag the (mocked) list and wait for the resulting local state commit. */
async function dragSequence(
view: Awaited<ReturnType<typeof renderSequences>>,
data: any[]
) {
const list = view.UNSAFE_getByType(DraggableFlatList)
await act(async () => {
list.props.onDragEnd({ data })
})
}
it('ADSEQ-01: shows the slots loading copy', () => { it('ADSEQ-01: shows the slots loading copy', () => {
setProcedure('admin.slots.getAll', { mode: 'pending' }) setProcedure('admin.slots.getAll', { mode: 'pending' })
const view = renderSequences() __setParams({ slotId: SLOT_ID })
const view = renderWithProviders(<DeliverySequences />, { auth: 'in' })
// Loading assertions stay synchronous: the query never settles.
expect(view.getByText('Loading slots...')).toBeTruthy() expect(view.getByText('Loading slots...')).toBeTruthy()
}) })
it('ADSEQ-02: with no slots shows the empty copy', () => { it('ADSEQ-02: with no slots shows the empty copy', async () => {
setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } }) setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } })
const view = renderSequences() const view = await renderSequences()
expect(view.getByText('No slots available')).toBeTruthy() expect(view.getByText('No slots available')).toBeTruthy()
}) })
it('ADSEQ-03: loads the slot selected through the URL', () => { it('ADSEQ-03: loads the slot selected through the URL', async () => {
const view = renderSequences() const view = await renderSequences()
expect(lastProcedureInput('admin.order.getSlotOrders')).toEqual({ slotId: SLOT_ID }) expect(lastProcedureInput('admin.order.getSlotOrders')).toEqual({ slotId: SLOT_ID })
expect(view.getByTestId('delivery-sequence-slot-dropdown')).toBeTruthy() expect(view.getByTestId('delivery-sequence-slot-dropdown')).toBeTruthy()
@ -81,16 +103,18 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
}) })
it('ADSEQ-04: with no slotId it replaces the URL with the first slot', async () => { it('ADSEQ-04: with no slotId it replaces the URL with the first slot', async () => {
renderSequences({}) const view = await renderSequences({})
await flush(2)
await waitFor(() =>
expect(router.replace).toHaveBeenCalledWith( expect(router.replace).toHaveBeenCalledWith(
'/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=1849', '/(drawer)/dashboard/manage-orders/delivery-sequences?slotId=1849',
) )
)
expect(view).toBeTruthy()
}) })
it('ADSEQ-05: choosing another slot replaces the URL', () => { it('ADSEQ-05: choosing another slot replaces the URL', async () => {
const view = renderSequences() const view = await renderSequences()
fireEvent.press(view.getByTestId('delivery-sequence-slot-dropdown')) fireEvent.press(view.getByTestId('delivery-sequence-slot-dropdown'))
fireEvent.press(view.getByTestId('delivery-sequence-slot-dropdown-option-1850')) fireEvent.press(view.getByTestId('delivery-sequence-slot-dropdown-option-1850'))
@ -100,22 +124,31 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
) )
}) })
it('ADSEQ-06: shows the orders loading copy', () => { it('ADSEQ-06: shows the orders loading copy', async () => {
// The slots query and the orders query mount together and would share one
// (never-settling) batch. Seed the slots query so only `getSlotOrders` is
// pending while the slot header renders.
setProcedure('admin.order.getSlotOrders', { mode: 'pending' }) setProcedure('admin.order.getSlotOrders', { mode: 'pending' })
const view = renderSequences() const queryClient = createTestQueryClient()
queryClient.setQueryData(
[['admin', 'slots', 'getAll'], { type: 'query' }],
{ slots: SLOTS, count: SLOTS.length },
)
__setParams({ slotId: SLOT_ID })
const view = await renderAndFlush(<DeliverySequences />, { auth: 'in', queryClient })
expect(view.getByText('Loading orders...')).toBeTruthy() expect(view.getByText('Loading orders...')).toBeTruthy()
}) })
it('ADSEQ-07: shows the no-orders copy', () => { it('ADSEQ-07: shows the no-orders copy', async () => {
slotOrders([]) slotOrders([])
const view = renderSequences() const view = await renderSequences()
expect(view.getByText('No orders found for this slot')).toBeTruthy() expect(view.getByText('No orders found for this slot')).toBeTruthy()
}) })
it('ADSEQ-08: renders the slot statistics', () => { it('ADSEQ-08: renders the slot statistics', async () => {
const view = renderSequences() const view = await renderSequences()
// The harness's DraggableFlatList mock renders rows only, so mount the real // The harness's DraggableFlatList mock renders rows only, so mount the real
// ListHeaderComponent (SlotProgress) that the page passes to it. // ListHeaderComponent (SlotProgress) that the page passes to it.
@ -131,8 +164,8 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
expect(stats.getAllByText('1')).toHaveLength(2) expect(stats.getAllByText('1')).toHaveLength(2)
}) })
it('ADSEQ-09: the staff filter lists Unassigned, All Users and staff', () => { it('ADSEQ-09: the staff filter lists Unassigned, All Users and staff', async () => {
const view = renderSequences() const view = await renderSequences()
fireEvent.press(view.getByTestId('delivery-sequence-user-dropdown')) fireEvent.press(view.getByTestId('delivery-sequence-user-dropdown'))
@ -149,13 +182,10 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
setProcedure('admin.slots.getDeliverySequence', { setProcedure('admin.slots.getDeliverySequence', {
data: { deliverySequence: { 3: [11] } }, data: { deliverySequence: { 3: [11] } },
}) })
const view = renderSequences() const view = await renderSequences()
selectUser(view, '3') selectUser(view, '3')
const list = view.UNSAFE_getByType(DraggableFlatList) await dragSequence(view, [{ sequenceId: 11 }])
await act(async () => {
list.props.onDragEnd({ data: [{ sequenceId: 11 }] })
})
expect(view.getByLabelText('Save sequence')).toBeTruthy() expect(view.getByLabelText('Save sequence')).toBeTruthy()
}) })
@ -164,37 +194,33 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
setProcedure('admin.slots.getDeliverySequence', { setProcedure('admin.slots.getDeliverySequence', {
data: { deliverySequence: { 3: [11] } }, data: { deliverySequence: { 3: [11] } },
}) })
const view = renderSequences() const view = await renderSequences()
selectUser(view, '3') selectUser(view, '3')
const list = view.UNSAFE_getByType(DraggableFlatList) await dragSequence(view, [{ sequenceId: 11 }])
await act(async () => {
list.props.onDragEnd({ data: [{ sequenceId: 11 }] })
})
fireEvent.press(view.getByLabelText('Save sequence')) fireEvent.press(view.getByLabelText('Save sequence'))
await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.slots.updateDeliverySequence')).toEqual({ expect(lastMutationInput('admin.slots.updateDeliverySequence')).toEqual({
id: 1849, id: 1849,
deliverySequence: { 3: [11] }, deliverySequence: { 3: [11] },
}) })
)
}) })
it('ADSEQ-12: a successful save shows the success alert', async () => { it('ADSEQ-12: a successful save shows the success alert', async () => {
setProcedure('admin.slots.getDeliverySequence', { setProcedure('admin.slots.getDeliverySequence', {
data: { deliverySequence: { 3: [11] } }, data: { deliverySequence: { 3: [11] } },
}) })
const view = renderSequences() const view = await renderSequences()
selectUser(view, '3') selectUser(view, '3')
const list = view.UNSAFE_getByType(DraggableFlatList) await dragSequence(view, [{ sequenceId: 11 }])
await act(async () => {
list.props.onDragEnd({ data: [{ sequenceId: 11 }] })
})
fireEvent.press(view.getByLabelText('Save sequence')) fireEvent.press(view.getByLabelText('Save sequence'))
await flush(2)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Delivery sequence updated successfully') expect(alertSpy).toHaveBeenCalledWith('Success', 'Delivery sequence updated successfully')
)
}) })
it('ADSEQ-13: a failed save shows the error alert', async () => { it('ADSEQ-13: a failed save shows the error alert', async () => {
@ -205,68 +231,69 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
setProcedure('admin.slots.getDeliverySequence', { setProcedure('admin.slots.getDeliverySequence', {
data: { deliverySequence: { 3: [11] } }, data: { deliverySequence: { 3: [11] } },
}) })
const view = renderSequences() const view = await renderSequences()
selectUser(view, '3') selectUser(view, '3')
const list = view.UNSAFE_getByType(DraggableFlatList) await dragSequence(view, [{ sequenceId: 11 }])
await act(async () => {
list.props.onDragEnd({ data: [{ sequenceId: 11 }] })
})
fireEvent.press(view.getByLabelText('Save sequence')) fireEvent.press(view.getByLabelText('Save sequence'))
await flush(2)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Error', 'Error',
'Failed to update delivery sequence: boom', 'Failed to update delivery sequence: boom',
) )
)
}) })
it('ADSEQ-14: marking packaged from the order menu calls updatePackaged', async () => { it('ADSEQ-14: marking packaged from the order menu calls updatePackaged', async () => {
const view = renderSequences() const view = await renderSequences()
fireEvent.press(view.getByTestId('sequence-menu-11')) fireEvent.press(view.getByTestId('sequence-menu-11'))
fireEvent(view.getByTestId('order-menu-packaged'), 'responderEnd', { fireEvent(view.getByTestId('order-menu-packaged'), 'responderEnd', {
stopPropagation: jest.fn(), stopPropagation: jest.fn(),
}) })
await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.order.updatePackaged')).toEqual({ expect(lastMutationInput('admin.order.updatePackaged')).toEqual({
orderId: '11', orderId: '11',
isPackaged: true, isPackaged: true,
}) })
)
}) })
it('ADSEQ-15: marking delivered from the order menu calls updateDelivered', async () => { it('ADSEQ-15: marking delivered from the order menu calls updateDelivered', async () => {
const view = renderSequences() const view = await renderSequences()
fireEvent.press(view.getByTestId('sequence-menu-11')) fireEvent.press(view.getByTestId('sequence-menu-11'))
fireEvent(view.getByTestId('order-menu-delivered'), 'responderEnd', { fireEvent(view.getByTestId('order-menu-delivered'), 'responderEnd', {
stopPropagation: jest.fn(), stopPropagation: jest.fn(),
}) })
await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.order.updateDelivered')).toEqual({ expect(lastMutationInput('admin.order.updateDelivered')).toEqual({
orderId: '11', orderId: '11',
isDelivered: true, isDelivered: true,
}) })
)
}) })
it('ADSEQ-16: Attach Location saves the current coordinates', async () => { it('ADSEQ-16: Attach Location saves the current coordinates', async () => {
const view = renderSequences() const view = await renderSequences()
fireEvent.press(view.getByTestId('sequence-menu-11')) fireEvent.press(view.getByTestId('sequence-menu-11'))
fireEvent.press(view.getByTestId('order-menu-attach-location')) fireEvent.press(view.getByTestId('order-menu-attach-location'))
await flush(3)
await waitFor(() =>
expect(lastMutationInput('admin.order.updateAddressCoords')).toEqual({ expect(lastMutationInput('admin.order.updateAddressCoords')).toEqual({
addressId: 11, addressId: 11,
latitude: 12.34, latitude: 12.34,
longitude: 56.78, longitude: 56.78,
}) })
)
}) })
it('ADSEQ-17: View Details opens the order detail route', () => { it('ADSEQ-17: View Details opens the order detail route', async () => {
const view = renderSequences() const view = await renderSequences()
fireEvent.press(view.getByTestId('sequence-menu-11')) fireEvent.press(view.getByTestId('sequence-menu-11'))
fireEvent.press(view.getByTestId('order-menu-view-details')) fireEvent.press(view.getByTestId('order-menu-view-details'))
@ -276,9 +303,9 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
) )
}) })
it('ADSEQ-18: a flash order is listed like any other order (no flash branch)', () => { it('ADSEQ-18: a flash order is listed like any other order (no flash branch)', async () => {
slotOrders([{ ...SLOT_ORDERS[0], id: 12, readableId: 102, isFlashDelivery: true }]) slotOrders([{ ...SLOT_ORDERS[0], id: 12, readableId: 102, isFlashDelivery: true }])
const view = renderSequences() const view = await renderSequences()
expect(view.getByText('#102')).toBeTruthy() expect(view.getByText('#102')).toBeTruthy()
expect(view.queryByText('FLASH')).toBeNull() expect(view.queryByText('FLASH')).toBeNull()
@ -286,7 +313,7 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
it('ADSEQ-19: registers the manual refresh listener and survives a refresh event', async () => { it('ADSEQ-19: registers the manual refresh listener and survives a refresh event', async () => {
const listenerSpy = jest.spyOn(DeviceEventEmitter, 'addListener') const listenerSpy = jest.spyOn(DeviceEventEmitter, 'addListener')
const view = renderSequences() const view = await renderSequences()
await flush() await flush()
expect(listenerSpy).toHaveBeenCalledWith('refresh_event', expect.any(Function)) expect(listenerSpy).toHaveBeenCalledWith('refresh_event', expect.any(Function))
@ -302,7 +329,7 @@ describe('Delivery sequences (ADSEQ-01..20)', () => {
it('ADSEQ-20: with no orders there is no sequence to save', async () => { it('ADSEQ-20: with no orders there is no sequence to save', async () => {
slotOrders([]) slotOrders([])
const view = renderSequences() const view = await renderSequences()
expect(view.getByText('No orders found for this slot')).toBeTruthy() expect(view.getByText('No orders found for this slot')).toBeTruthy()
expect(view.queryByLabelText('Save sequence')).toBeNull() expect(view.queryByLabelText('Save sequence')).toBeNull()

View file

@ -72,7 +72,9 @@ describe('Login (ALOGIN-01..14)', () => {
fireEvent.press(view.getByTestId('login-button')) fireEvent.press(view.getByTestId('login-button'))
await flush(2) await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.staffUser.login')).toEqual({ name: 'Admin One', password: 'secret' }) expect(lastMutationInput('admin.staffUser.login')).toEqual({ name: 'Admin One', password: 'secret' })
)
}) })
it('ALOGIN-06: the password is sent exactly as typed (not trimmed)', async () => { it('ALOGIN-06: the password is sent exactly as typed (not trimmed)', async () => {
@ -83,10 +85,12 @@ describe('Login (ALOGIN-01..14)', () => {
fireEvent.press(view.getByTestId('login-button')) fireEvent.press(view.getByTestId('login-button'))
await flush(2) await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.staffUser.login')).toEqual({ expect(lastMutationInput('admin.staffUser.login')).toEqual({
name: 'Admin One', name: 'Admin One',
password: ' pass word ', password: ' pass word ',
}) })
)
}) })
it('ALOGIN-07: success persists the JWT + staff and replaces to the dashboard', async () => { it('ALOGIN-07: success persists the JWT + staff and replaces to the dashboard', async () => {
@ -119,15 +123,14 @@ describe('Login (ALOGIN-01..14)', () => {
}) })
it('ALOGIN-09: a server error without a message shows "Login failed"', async () => { it('ALOGIN-09: a server error without a message shows "Login failed"', async () => {
setProcedure('admin.staffUser.login', { mode: 'error', error: { message: '' } }) setProcedure('admin.staffUser.login', { mode: 'error', error: new Error('') })
const view = renderWithProviders(<Login />, { auth: 'out' }) const view = renderWithProviders(<Login />, { auth: 'out' })
fireEvent.changeText(view.getByTestId('login-name-input'), 'Admin One') fireEvent.changeText(view.getByTestId('login-name-input'), 'Admin One')
fireEvent.changeText(view.getByTestId('login-password-input'), 'wrong') fireEvent.changeText(view.getByTestId('login-password-input'), 'wrong')
fireEvent.press(view.getByTestId('login-button')) fireEvent.press(view.getByTestId('login-button'))
await flush(3)
expect(view.getByText('Login failed')).toBeTruthy() expect(await view.findByText('Login failed')).toBeTruthy()
}) })
it('ALOGIN-10: a pending login shows "Logging in..." and disables the button', async () => { it('ALOGIN-10: a pending login shows "Logging in..." and disables the button', async () => {

View file

@ -8,7 +8,7 @@ import { Alert, Text } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent } from '@testing-library/react-native'
import ManageOrders from '@/app/(drawer)/dashboard/manage-orders/index' import ManageOrders from '@/app/(drawer)/dashboard/manage-orders/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, procedureQueryCalls } from '../mocks/trpc-client' import { setProcedure, procedureQueryCalls } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
@ -37,17 +37,18 @@ describe('Manage orders hub (AMHUB-01..09)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
/** Render and let the slots query resolve (real tRPC client + React Query). */
function renderHub() { function renderHub() {
return renderWithProviders(<ManageOrders />, { auth: 'in' }) return renderAndFlush(<ManageOrders />, { auth: 'in' })
} }
function selectOption(view: ReturnType<typeof renderHub>, value: string) { function selectOption(view: Awaited<ReturnType<typeof renderHub>>, value: string) {
fireEvent.press(view.getByTestId('manage-orders-slot-dropdown')) fireEvent.press(view.getByTestId('manage-orders-slot-dropdown'))
fireEvent.press(view.getByTestId(`manage-orders-slot-dropdown-option-${value}`)) fireEvent.press(view.getByTestId(`manage-orders-slot-dropdown-option-${value}`))
} }
it('AMHUB-01: renders the two order actions and the slot dropdown', () => { it('AMHUB-01: renders the two order actions and the slot dropdown', async () => {
const view = renderHub() const view = await renderHub()
expect(view.getByText('Delivery Sequences')).toBeTruthy() expect(view.getByText('Delivery Sequences')).toBeTruthy()
expect(view.getByText('Orders')).toBeTruthy() expect(view.getByText('Orders')).toBeTruthy()
@ -57,15 +58,16 @@ describe('Manage orders hub (AMHUB-01..09)', () => {
it('AMHUB-02: renders without crashing while slots are loading', () => { it('AMHUB-02: renders without crashing while slots are loading', () => {
setProcedure('admin.slots.getAll', { mode: 'pending' }) setProcedure('admin.slots.getAll', { mode: 'pending' })
const view = renderHub() // Pending assertion: the page renders before the slots query settles.
const view = renderWithProviders(<ManageOrders />, { auth: 'in' })
expect(view.getByText('Delivery Sequences')).toBeTruthy() expect(view.getByText('Delivery Sequences')).toBeTruthy()
expect(view.getByText('Orders')).toBeTruthy() expect(view.getByText('Orders')).toBeTruthy()
}) })
it('AMHUB-03: with no slots the dropdown only offers Flash Deliveries', () => { it('AMHUB-03: with no slots the dropdown only offers Flash Deliveries', async () => {
setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } }) setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } })
const view = renderHub() const view = await renderHub()
fireEvent.press(view.getByTestId('manage-orders-slot-dropdown')) fireEvent.press(view.getByTestId('manage-orders-slot-dropdown'))
@ -73,8 +75,8 @@ describe('Manage orders hub (AMHUB-01..09)', () => {
expect(view.queryByTestId('manage-orders-slot-dropdown-option-1849')).toBeNull() expect(view.queryByTestId('manage-orders-slot-dropdown-option-1849')).toBeNull()
}) })
it('AMHUB-04: Delivery Sequences pushes the route with the selected slot id', () => { it('AMHUB-04: Delivery Sequences pushes the route with the selected slot id', async () => {
const view = renderHub() const view = await renderHub()
selectOption(view, '1849') selectOption(view, '1849')
fireEvent.press(view.getByText('Delivery Sequences')) fireEvent.press(view.getByText('Delivery Sequences'))
@ -84,8 +86,8 @@ describe('Manage orders hub (AMHUB-01..09)', () => {
) )
}) })
it('AMHUB-05: Flash selected alerts that flash deliveries have no sequence', () => { it('AMHUB-05: Flash selected alerts that flash deliveries have no sequence', async () => {
const view = renderHub() const view = await renderHub()
selectOption(view, 'flash') selectOption(view, 'flash')
fireEvent.press(view.getByText('Delivery Sequences')) fireEvent.press(view.getByText('Delivery Sequences'))
@ -97,16 +99,16 @@ describe('Manage orders hub (AMHUB-01..09)', () => {
expect(router.push).not.toHaveBeenCalled() expect(router.push).not.toHaveBeenCalled()
}) })
it('AMHUB-06: Orders opens the regular order list', () => { it('AMHUB-06: Orders opens the regular order list', async () => {
const view = renderHub() const view = await renderHub()
fireEvent.press(view.getByText('Orders')) fireEvent.press(view.getByText('Orders'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders/orders') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders/orders')
}) })
it('AMHUB-07: Orders with Flash selected opens the flash-filtered list', () => { it('AMHUB-07: Orders with Flash selected opens the flash-filtered list', async () => {
const view = renderHub() const view = await renderHub()
selectOption(view, 'flash') selectOption(view, 'flash')
fireEvent.press(view.getByText('Orders')) fireEvent.press(view.getByText('Orders'))
@ -116,8 +118,8 @@ describe('Manage orders hub (AMHUB-01..09)', () => {
) )
}) })
it('AMHUB-08: a queued navigation target is pushed once and consumed', () => { it('AMHUB-08: a queued navigation target is pushed once and consumed', async () => {
const view = renderWithProviders( const view = await renderAndFlush(
<> <>
<NavigationSeed /> <NavigationSeed />
<ManageOrders /> <ManageOrders />
@ -131,12 +133,12 @@ describe('Manage orders hub (AMHUB-01..09)', () => {
}) })
it('AMHUB-09: the slots query is mounted for the refresh/focus fetcher', async () => { it('AMHUB-09: the slots query is mounted for the refresh/focus fetcher', async () => {
const view = renderHub() const view = await renderHub()
await flush()
// The harness's useFocusEffect mock runs on mount only, so the second-focus // The harness's useFocusEffect mock runs on mount only, so the second-focus
// callback (useMarkDataFetchers) cannot be observed; the fetcher source is // callback (useMarkDataFetchers) cannot be observed; the fetcher source is
// still asserted to be wired. // still asserted to be wired.
await flush()
expect(procedureQueryCalls('admin.slots.getAll').length).toBeGreaterThanOrEqual(1) expect(procedureQueryCalls('admin.slots.getAll').length).toBeGreaterThanOrEqual(1)
expect(view.getByText('Delivery Sequences')).toBeTruthy() expect(view.getByText('Delivery Sequences')).toBeTruthy()
}) })

View file

@ -5,10 +5,10 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import OrderDetails from '@/app/(drawer)/dashboard/manage-orders/order-details/[id]' import OrderDetails from '@/app/(drawer)/dashboard/manage-orders/order-details/[id]'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
@ -50,41 +50,43 @@ describe('Order details (AOD-01..25)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
/** Render and let the initial queries resolve (real tRPC client + React Query). */
function renderDetails() { function renderDetails() {
return renderWithProviders(<OrderDetails />, { auth: 'in' }) return renderAndFlush(<OrderDetails />, { auth: 'in' })
} }
it('AOD-01: shows the loading copy', () => { it('AOD-01: shows the loading copy', () => {
setProcedure('admin.order.getOrderDetails', { mode: 'pending' }) setProcedure('admin.order.getOrderDetails', { mode: 'pending' })
const view = renderDetails() const view = renderWithProviders(<OrderDetails />, { auth: 'in' })
// Loading assertions stay synchronous: the query never settles.
expect(view.getByText('Loading order details...')).toBeTruthy() expect(view.getByText('Loading order details...')).toBeTruthy()
}) })
it('AOD-02: a failed load shows the error message and Go Back', () => { it('AOD-02: a failed load shows the error message and Go Back', async () => {
setProcedure('admin.order.getOrderDetails', { setProcedure('admin.order.getOrderDetails', {
mode: 'error', mode: 'error',
error: new Error('Order not found'), error: new Error('Order not found'),
}) })
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Oops!')).toBeTruthy() expect(await view.findByText('Oops!')).toBeTruthy()
expect(view.getByText('Order not found')).toBeTruthy() expect(view.getByText('Order not found')).toBeTruthy()
fireEvent.press(view.getByText('Go Back')) fireEvent.press(view.getByText('Go Back'))
expect(router.back).toHaveBeenCalledTimes(1) expect(router.back).toHaveBeenCalledTimes(1)
}) })
it('AOD-03: a missing id disables the query', () => { it('AOD-03: a missing id disables the query', async () => {
__setParams({}) __setParams({})
const view = renderDetails() const view = await renderDetails()
expect(procedureQueryCalls('admin.order.getOrderDetails')).toHaveLength(0) expect(procedureQueryCalls('admin.order.getOrderDetails')).toHaveLength(0)
expect(view.getByText('Failed to load order details')).toBeTruthy() expect(view.getByText('Failed to load order details')).toBeTruthy()
}) })
it('AOD-04: renders the header with id, date and status', () => { it('AOD-04: renders the header with id, date and status', async () => {
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Order ID')).toBeTruthy() expect(view.getByText('Order ID')).toBeTruthy()
expect(view.getByText('#101')).toBeTruthy() expect(view.getByText('#101')).toBeTruthy()
@ -93,20 +95,20 @@ describe('Order details (AOD-01..25)', () => {
expect(view.getByText(/Delivery at:/)).toBeTruthy() expect(view.getByText(/Delivery at:/)).toBeTruthy()
}) })
it('AOD-05: a cancelled order shows the cancellation reason block', () => { it('AOD-05: a cancelled order shows the cancellation reason block', async () => {
setProcedure('admin.order.getOrderDetails', { setProcedure('admin.order.getOrderDetails', {
data: { data: {
...order({ status: 'cancelled', cancelReason: 'Customer changed their mind' }), ...order({ status: 'cancelled', cancelReason: 'Customer changed their mind' }),
}, },
}) })
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Cancellation Reason')).toBeTruthy() expect(view.getByText('Cancellation Reason')).toBeTruthy()
expect(view.getByText('Customer changed their mind')).toBeTruthy() expect(view.getByText('Customer changed their mind')).toBeTruthy()
}) })
it('AOD-06: renders the customer card and links to the user', () => { it('AOD-06: renders the customer card and links to the user', async () => {
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Customer Details')).toBeTruthy() expect(view.getByText('Customer Details')).toBeTruthy()
expect(view.getByText('Test User')).toBeTruthy() expect(view.getByText('Test User')).toBeTruthy()
@ -117,8 +119,8 @@ describe('Order details (AOD-01..25)', () => {
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
}) })
it('AOD-07: renders each item with quantity, price and packaging controls', () => { it('AOD-07: renders each item with quantity, price and packaging controls', async () => {
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Chicken Breast')).toBeTruthy() expect(view.getByText('Chicken Breast')).toBeTruthy()
expect(view.getByText('2 x 500g × ₹215')).toBeTruthy() expect(view.getByText('2 x 500g × ₹215')).toBeTruthy()
@ -131,39 +133,39 @@ describe('Order details (AOD-01..25)', () => {
}) })
it('AOD-08: the Packaged control calls updateOrderItemPackaging', async () => { it('AOD-08: the Packaged control calls updateOrderItemPackaging', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-item-packaged-1')) fireEvent.press(view.getByTestId('order-item-packaged-1'))
await flush(2) await waitFor(() =>
expect(lastMutationInput('admin.order.updateOrderItemPackaging')).toEqual({ expect(lastMutationInput('admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 1, orderItemId: 1,
isPackaged: true, isPackaged: true,
}) })
)
}) })
it('AOD-09: the Pkg Verified control calls updateOrderItemPackaging', async () => { it('AOD-09: the Pkg Verified control calls updateOrderItemPackaging', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-item-verified-1')) fireEvent.press(view.getByTestId('order-item-verified-1'))
await flush(2) await waitFor(() =>
expect(lastMutationInput('admin.order.updateOrderItemPackaging')).toEqual({ expect(lastMutationInput('admin.order.updateOrderItemPackaging')).toEqual({
orderItemId: 1, orderItemId: 1,
isPackageVerified: true, isPackageVerified: true,
}) })
)
}) })
it('AOD-10: a pending item update disables the item control', async () => { it('AOD-10: a pending item update disables the item control', async () => {
setProcedure('admin.order.updateOrderItemPackaging', { mode: 'pending' }) setProcedure('admin.order.updateOrderItemPackaging', { mode: 'pending' })
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-item-packaged-1')) fireEvent.press(view.getByTestId('order-item-packaged-1'))
await flush(2) await waitFor(() =>
expect( expect(
view.getByTestId('order-item-packaged-1').props.accessibilityState?.disabled, view.getByTestId('order-item-packaged-1').props.accessibilityState?.disabled,
).toBe(true) ).toBe(true)
)
}) })
it('AOD-11: a failed item update shows an alert', async () => { it('AOD-11: a failed item update shows an alert', async () => {
@ -171,16 +173,14 @@ describe('Order details (AOD-01..25)', () => {
mode: 'error', mode: 'error',
error: new Error('boom'), error: new Error('boom'),
}) })
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-item-verified-1')) fireEvent.press(view.getByTestId('order-item-verified-1'))
await flush(2) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'boom'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
}) })
it('AOD-12: renders the bill summary', () => { it('AOD-12: renders the bill summary', async () => {
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Subtotal (2 items)')).toBeTruthy() expect(view.getByText('Subtotal (2 items)')).toBeTruthy()
expect(view.getAllByText('₹445').length).toBe(2) expect(view.getAllByText('₹445').length).toBe(2)
@ -190,7 +190,7 @@ describe('Order details (AOD-01..25)', () => {
}) })
it('AOD-13: removing the delivery charge confirms and calls the mutation', async () => { it('AOD-13: removing the delivery charge confirms and calls the mutation', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('remove-delivery-charge')) fireEvent.press(view.getByTestId('remove-delivery-charge'))
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
@ -202,10 +202,12 @@ describe('Order details (AOD-01..25)', () => {
await act(async () => { await act(async () => {
pressAlertButton(alertSpy, 'Remove') pressAlertButton(alertSpy, 'Remove')
}) })
await flush(2) await waitFor(() =>
expect(lastMutationInput('admin.order.removeDeliveryCharge')).toEqual({ orderId: 11 }) expect(lastMutationInput('admin.order.removeDeliveryCharge')).toEqual({ orderId: 11 })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Delivery charge has been removed') expect(alertSpy).toHaveBeenCalledWith('Success', 'Delivery charge has been removed')
)
}) })
it('AOD-14: a failed remove shows an alert', async () => { it('AOD-14: a failed remove shows an alert', async () => {
@ -213,26 +215,24 @@ describe('Order details (AOD-01..25)', () => {
mode: 'error', mode: 'error',
error: new Error('boom'), error: new Error('boom'),
}) })
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('remove-delivery-charge')) fireEvent.press(view.getByTestId('remove-delivery-charge'))
await act(async () => { await act(async () => {
pressAlertButton(alertSpy, 'Remove') pressAlertButton(alertSpy, 'Remove')
}) })
await flush(2) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'boom'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
}) })
it('AOD-15: a zero delivery charge hides the remove action', () => { it('AOD-15: a zero delivery charge hides the remove action', async () => {
setProcedure('admin.order.getOrderDetails', { data: order({ deliveryCharge: 0 }) }) setProcedure('admin.order.getOrderDetails', { data: order({ deliveryCharge: 0 }) })
const view = renderDetails() const view = await renderDetails()
expect(view.queryByTestId('remove-delivery-charge')).toBeNull() expect(view.queryByTestId('remove-delivery-charge')).toBeNull()
expect(view.queryByText('Delivery Charge')).toBeNull() expect(view.queryByText('Delivery Charge')).toBeNull()
}) })
it('AOD-16: an applied coupon renders the coupon block', () => { it('AOD-16: an applied coupon renders the coupon block', async () => {
setProcedure('admin.order.getOrderDetails', { setProcedure('admin.order.getOrderDetails', {
data: order({ data: order({
couponCode: 'SAVE10', couponCode: 'SAVE10',
@ -240,7 +240,7 @@ describe('Order details (AOD-01..25)', () => {
discountAmount: 20, discountAmount: 20,
}), }),
}) })
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Coupon Applied')).toBeTruthy() expect(view.getByText('Coupon Applied')).toBeTruthy()
expect(view.getByText('SAVE10')).toBeTruthy() expect(view.getByText('SAVE10')).toBeTruthy()
@ -249,22 +249,22 @@ describe('Order details (AOD-01..25)', () => {
expect(view.getAllByText('-₹20').length).toBeGreaterThanOrEqual(1) expect(view.getAllByText('-₹20').length).toBeGreaterThanOrEqual(1)
}) })
it('AOD-17: a flash order renders the amber flash notice', () => { it('AOD-17: a flash order renders the amber flash notice', async () => {
setProcedure('admin.order.getOrderDetails', { setProcedure('admin.order.getOrderDetails', {
data: order({ isFlashDelivery: true }), data: order({ isFlashDelivery: true }),
}) })
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('1 Hr Delivery Order')).toBeTruthy() expect(view.getByText('1 Hr Delivery Order')).toBeTruthy()
expect(view.getByText('⚡ 1 Hr Delivery • High Priority')).toBeTruthy() expect(view.getByText('⚡ 1 Hr Delivery • High Priority')).toBeTruthy()
expect(view.getByText(/Expected Delivery:/)).toBeTruthy() expect(view.getByText(/Expected Delivery:/)).toBeTruthy()
}) })
it('AOD-18: admin notes render, user notes are not displayed (current)', () => { it('AOD-18: admin notes render, user notes are not displayed (current)', async () => {
setProcedure('admin.order.getOrderDetails', { setProcedure('admin.order.getOrderDetails', {
data: order({ adminNotes: 'Call before delivery' }), data: order({ adminNotes: 'Call before delivery' }),
}) })
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Admin Notes')).toBeTruthy() expect(view.getByText('Admin Notes')).toBeTruthy()
expect(view.getByText('Call before delivery')).toBeTruthy() expect(view.getByText('Call before delivery')).toBeTruthy()
@ -272,8 +272,8 @@ describe('Order details (AOD-01..25)', () => {
expect(view.queryByText('Leave at door')).toBeNull() expect(view.queryByText('Leave at door')).toBeNull()
}) })
it('AOD-19: Cancel Order opens the cancellation dialog', () => { it('AOD-19: Cancel Order opens the cancellation dialog', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-details-cancel-button')) fireEvent.press(view.getByTestId('order-details-cancel-button'))
@ -283,19 +283,20 @@ describe('Order details (AOD-01..25)', () => {
).toBeTruthy() ).toBeTruthy()
}) })
it('AOD-20: an empty cancellation reason is blocked', () => { it('AOD-20: an empty cancellation reason is blocked', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-details-cancel-button')) fireEvent.press(view.getByTestId('order-details-cancel-button'))
const buttons = view.getAllByText('Cancel Order') const buttons = view.getAllByText('Cancel Order')
fireEvent.press(buttons[buttons.length - 1]) fireEvent.press(buttons[buttons.length - 1])
await flush(2)
expect(procedureMutationCalls('admin.order.cancelOrder')).toHaveLength(0) expect(procedureMutationCalls('admin.order.cancelOrder')).toHaveLength(0)
expect(alertSpy).not.toHaveBeenCalled() expect(alertSpy).not.toHaveBeenCalled()
}) })
it('AOD-21: confirming cancellation calls cancelOrder with the reason', async () => { it('AOD-21: confirming cancellation calls cancelOrder with the reason', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-details-cancel-button')) fireEvent.press(view.getByTestId('order-details-cancel-button'))
fireEvent.changeText(view.getByTestId('cancel-order-reason'), 'Customer requested') fireEvent.changeText(view.getByTestId('cancel-order-reason'), 'Customer requested')
@ -310,17 +311,17 @@ describe('Order details (AOD-01..25)', () => {
await act(async () => { await act(async () => {
pressAlertButton(alertSpy, 'Yes, Cancel') pressAlertButton(alertSpy, 'Yes, Cancel')
}) })
await flush(2) await waitFor(() =>
expect(lastMutationInput('admin.order.cancelOrder')).toEqual({ expect(lastMutationInput('admin.order.cancelOrder')).toEqual({
orderId: 11, orderId: 11,
reason: 'Customer requested', reason: 'Customer requested',
}) })
)
}) })
it('AOD-22: a failed cancellation shows an alert', async () => { it('AOD-22: a failed cancellation shows an alert', async () => {
setProcedure('admin.order.cancelOrder', { mode: 'error', error: new Error('boom') }) setProcedure('admin.order.cancelOrder', { mode: 'error', error: new Error('boom') })
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-details-cancel-button')) fireEvent.press(view.getByTestId('order-details-cancel-button'))
fireEvent.changeText(view.getByTestId('cancel-order-reason'), 'Customer requested') fireEvent.changeText(view.getByTestId('cancel-order-reason'), 'Customer requested')
@ -329,29 +330,27 @@ describe('Order details (AOD-01..25)', () => {
await act(async () => { await act(async () => {
pressAlertButton(alertSpy, 'Yes, Cancel') pressAlertButton(alertSpy, 'Yes, Cancel')
}) })
await flush(2) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'boom'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
}) })
it('AOD-23: Manage Orders returns to the orders hub', () => { it('AOD-23: Manage Orders returns to the orders hub', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('order-details-back-button')) fireEvent.press(view.getByTestId('order-details-back-button'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/manage-orders')
}) })
it('AOD-24: the customer card opens the user detail route', () => { it('AOD-24: the customer card opens the user detail route', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('customer-details-card')) fireEvent.press(view.getByTestId('customer-details-card'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/user-management/5')
}) })
it('AOD-25: the details screen renders no OrderOptionsMenu', () => { it('AOD-25: the details screen renders no OrderOptionsMenu', async () => {
const view = renderDetails() const view = await renderDetails()
expect(view.queryByText('Select an action to perform')).toBeNull() expect(view.queryByText('Select an action to perform')).toBeNull()
expect(view.queryByText('View Details')).toBeNull() expect(view.queryByText('View Details')).toBeNull()

View file

@ -5,10 +5,10 @@
*/ */
import React from 'react' import React from 'react'
import { ActivityIndicator, Alert, FlatList, Modal, RefreshControl } from 'react-native' import { ActivityIndicator, Alert, FlatList, Modal, RefreshControl } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import Orders from '@/app/(drawer)/dashboard/manage-orders/orders/index' import Orders from '@/app/(drawer)/dashboard/manage-orders/orders/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
@ -26,7 +26,8 @@ import {
} from '../fixtures' } from '../fixtures'
function setOrders(orders: any[]) { function setOrders(orders: any[]) {
setProcedure('admin.order.getAll', { data: { pages: [{ orders }] } }) // The real `useInfiniteQuery` wraps each procedure response into one page.
setProcedure('admin.order.getAll', { data: { orders } })
} }
describe('Orders list (AORDUI-01..36)', () => { describe('Orders list (AORDUI-01..36)', () => {
@ -44,15 +45,16 @@ describe('Orders list (AORDUI-01..36)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
/** Render and let the initial queries resolve (real tRPC client + React Query). */
function renderOrders() { function renderOrders() {
return renderWithProviders(<Orders />, { auth: 'in' }) return renderAndFlush(<Orders />, { auth: 'in' })
} }
function openFilters(view: ReturnType<typeof renderOrders>) { function openFilters(view: Awaited<ReturnType<typeof renderOrders>>) {
fireEvent.press(view.getByTestId('orders-filter-button')) fireEvent.press(view.getByTestId('orders-filter-button'))
} }
function closeTopDialog(view: ReturnType<typeof renderOrders>) { function closeTopDialog(view: Awaited<ReturnType<typeof renderOrders>>) {
const modal = view.UNSAFE_getAllByType(Modal).find((candidate) => candidate.props.visible) const modal = view.UNSAFE_getAllByType(Modal).find((candidate) => candidate.props.visible)
if (!modal) throw new Error('No visible dialog to close') if (!modal) throw new Error('No visible dialog to close')
fireEvent(modal, 'requestClose') fireEvent(modal, 'requestClose')
@ -62,16 +64,46 @@ describe('Orders list (AORDUI-01..36)', () => {
return lastProcedureInput('admin.order.getAll') return lastProcedureInput('admin.order.getAll')
} }
type OrdersView = Awaited<ReturnType<typeof renderOrders>>
/**
* Input of the getAll infinite query the page currently observes. Unlike the
* last network call this also reflects a return to an already-cached filter
* (React Query does not re-request with `staleTime: Infinity`).
*/
function activeOrdersInput(view: OrdersView) {
const query = view.queryClient.getQueryCache().findAll({ type: 'active' }).find((candidate) => {
const key = candidate.queryKey as any
const path = Array.isArray(key?.[0]) ? (key[0] as string[]).join('.') : String(key?.[0])
return path === 'admin.order.getAll'
})
const key = query?.queryKey as any
return key?.[1]?.input
}
async function expectOrdersInput(view: OrdersView, expected: Record<string, unknown>) {
await waitFor(() => expect(activeOrdersInput(view)).toMatchObject(expected))
}
/**
* A changed filter is a new query key: until it resolves the page renders the
* loading copy, which unmounts the filter dialog. Wait for it to come back.
*/
async function expectFiltersVisible(view: OrdersView) {
await waitFor(() => expect(view.getByTestId('filter-packaged')).toBeTruthy())
}
it('AORDUI-01: shows the loading copy', () => { it('AORDUI-01: shows the loading copy', () => {
setProcedure('admin.order.getAll', { mode: 'pending' }) setProcedure('admin.order.getAll', { mode: 'pending' })
const view = renderOrders() const view = renderWithProviders(<Orders />, { auth: 'in' })
// Loading assertions stay synchronous: the query never settles.
expect(view.getByText('Loading orders...')).toBeTruthy() expect(view.getByText('Loading orders...')).toBeTruthy()
}) })
it('AORDUI-02: renders no order rows for an empty page (no empty copy exists)', () => { it('AORDUI-02: renders no order rows for an empty page (no empty copy exists)', async () => {
setOrders([]) setOrders([])
const view = renderOrders() const view = await renderOrders()
// Current page has no ListEmptyComponent: the header still renders, but no row. // Current page has no ListEmptyComponent: the header still renders, but no row.
expect(view.getByText('All slots')).toBeTruthy() expect(view.getByText('All slots')).toBeTruthy()
@ -79,9 +111,9 @@ describe('Orders list (AORDUI-01..36)', () => {
expect(view.queryByTestId('order-card-11')).toBeNull() expect(view.queryByTestId('order-card-11')).toBeNull()
}) })
it('AORDUI-03: renders the order card fields', () => { it('AORDUI-03: renders the order card fields', async () => {
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
expect(view.getByText('Test User')).toBeTruthy() expect(view.getByText('Test User')).toBeTruthy()
expect(view.getByText('#101')).toBeTruthy() expect(view.getByText('#101')).toBeTruthy()
@ -93,39 +125,39 @@ describe('Orders list (AORDUI-01..36)', () => {
expect(view.queryByText('pending')).toBeNull() expect(view.queryByText('pending')).toBeNull()
}) })
it('AORDUI-04: a flash order shows the FLASH badge', () => { it('AORDUI-04: a flash order shows the FLASH badge', async () => {
setOrders([ORDER_FLASH]) setOrders([ORDER_FLASH])
const view = renderOrders() const view = await renderOrders()
expect(view.getByText('FLASH')).toBeTruthy() expect(view.getByText('FLASH')).toBeTruthy()
expect(view.getByText('1 Hour Delivery • High Priority')).toBeTruthy() expect(view.getByText('1 Hour Delivery • High Priority')).toBeTruthy()
}) })
it('AORDUI-05: a negative customer is flagged', () => { it('AORDUI-05: a negative customer is flagged', async () => {
setOrders([ORDER_NEGATIVE]) setOrders([ORDER_NEGATIVE])
const view = renderOrders() const view = await renderOrders()
expect(view.getByText('Negative Customer')).toBeTruthy() expect(view.getByText('Negative Customer')).toBeTruthy()
}) })
it('AORDUI-06: a cancelled order shows the cancelled banner', () => { it('AORDUI-06: a cancelled order shows the cancelled banner', async () => {
setOrders([ORDER_CANCELLED]) setOrders([ORDER_CANCELLED])
const view = renderOrders() const view = await renderOrders()
expect(view.getByText('CANCELLED')).toBeTruthy() expect(view.getByText('CANCELLED')).toBeTruthy()
}) })
it('AORDUI-07: the delivery charge is displayed', () => { it('AORDUI-07: the delivery charge is displayed', async () => {
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
expect(view.getByText('Delivery Charge')).toBeTruthy() expect(view.getByText('Delivery Charge')).toBeTruthy()
expect(view.getByText('₹15')).toBeTruthy() expect(view.getByText('₹15')).toBeTruthy()
}) })
it('AORDUI-08: tapping User Notes opens the note dialog', () => { it('AORDUI-08: tapping User Notes opens the note dialog', async () => {
setOrders([{ ...ORDER_1, userNotes: 'Please call before delivery' }]) setOrders([{ ...ORDER_1, userNotes: 'Please call before delivery' }])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-user-notes-11')) fireEvent.press(view.getByTestId('order-user-notes-11'))
@ -133,9 +165,9 @@ describe('Orders list (AORDUI-01..36)', () => {
expect(view.getByText('Please call before delivery')).toBeTruthy() expect(view.getByText('Please call before delivery')).toBeTruthy()
}) })
it('AORDUI-09: tapping Admin Notes opens the notes form', () => { it('AORDUI-09: tapping Admin Notes opens the notes form', async () => {
setOrders([{ ...ORDER_1, adminNotes: 'Handle carefully' }]) setOrders([{ ...ORDER_1, adminNotes: 'Handle carefully' }])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-admin-notes-11')) fireEvent.press(view.getByTestId('order-admin-notes-11'))
@ -143,7 +175,7 @@ describe('Orders list (AORDUI-01..36)', () => {
expect(view.getByPlaceholderText('Enter admin notes...')).toBeTruthy() expect(view.getByPlaceholderText('Enter admin notes...')).toBeTruthy()
}) })
it('AORDUI-10: applied coupons are shown with code and discount', () => { it('AORDUI-10: applied coupons are shown with code and discount', async () => {
setOrders([ setOrders([
{ {
...ORDER_1, ...ORDER_1,
@ -152,7 +184,7 @@ describe('Orders list (AORDUI-01..36)', () => {
discountAmount: 20, discountAmount: 20,
}, },
]) ])
const view = renderOrders() const view = await renderOrders()
expect(view.getByText('Applied Coupons')).toBeTruthy() expect(view.getByText('Applied Coupons')).toBeTruthy()
expect(view.getByText('SAVE10')).toBeTruthy() expect(view.getByText('SAVE10')).toBeTruthy()
@ -162,13 +194,17 @@ describe('Orders list (AORDUI-01..36)', () => {
it('AORDUI-11: item packaging toggles call updateOrderItemPackaging', async () => { it('AORDUI-11: item packaging toggles call updateOrderItemPackaging', async () => {
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-items-11')) fireEvent.press(view.getByTestId('order-items-11'))
fireEvent.press(view.getByTestId('order-item-packaged-1')) fireEvent.press(view.getByTestId('order-item-packaged-1'))
await flush(2) await waitFor(() =>
expect(procedureMutationCalls('admin.order.updateOrderItemPackaging')).toHaveLength(1)
)
fireEvent.press(view.getByTestId('order-item-verified-1')) fireEvent.press(view.getByTestId('order-item-verified-1'))
await flush(2) await waitFor(() =>
expect(procedureMutationCalls('admin.order.updateOrderItemPackaging')).toHaveLength(2)
)
expect(procedureMutationCalls('admin.order.updateOrderItemPackaging')).toEqual([ expect(procedureMutationCalls('admin.order.updateOrderItemPackaging')).toEqual([
{ orderItemId: 1, isPackaged: true }, { orderItemId: 1, isPackaged: true },
@ -179,7 +215,7 @@ describe('Orders list (AORDUI-01..36)', () => {
it('AORDUI-12: an item being updated shows the pending indicator', async () => { it('AORDUI-12: an item being updated shows the pending indicator', async () => {
setProcedure('admin.order.updateOrderItemPackaging', { mode: 'pending' }) setProcedure('admin.order.updateOrderItemPackaging', { mode: 'pending' })
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-items-11')) fireEvent.press(view.getByTestId('order-items-11'))
fireEvent.press(view.getByTestId('order-item-packaged-1')) fireEvent.press(view.getByTestId('order-item-packaged-1'))
@ -194,52 +230,53 @@ describe('Orders list (AORDUI-01..36)', () => {
error: new Error('boom'), error: new Error('boom'),
}) })
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-items-11')) fireEvent.press(view.getByTestId('order-items-11'))
fireEvent.press(view.getByTestId('order-item-packaged-1')) fireEvent.press(view.getByTestId('order-item-packaged-1'))
await flush(2) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'boom'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
}) })
it('AORDUI-14: the inline Packaged toggle is inert (current gap)', () => { it('AORDUI-14: the inline Packaged toggle is inert (current gap)', async () => {
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-packaged-11')) fireEvent.press(view.getByTestId('order-packaged-11'))
await flush(2)
expect(procedureMutationCalls('admin.order.updatePackaged')).toHaveLength(0) expect(procedureMutationCalls('admin.order.updatePackaged')).toHaveLength(0)
}) })
it('AORDUI-15: the Delivered toggle calls updateDelivered', async () => { it('AORDUI-15: the Delivered toggle calls updateDelivered', async () => {
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-delivered-11')) fireEvent.press(view.getByTestId('order-delivered-11'))
await flush(2) await waitFor(() =>
expect(lastMutationInput('admin.order.updateDelivered')).toEqual({ expect(lastMutationInput('admin.order.updateDelivered')).toEqual({
orderId: 'ORD-1011', orderId: 'ORD-1011',
isDelivered: true, isDelivered: true,
}) })
)
}) })
it('AORDUI-16: a failed Delivered toggle is swallowed (current gap)', async () => { it('AORDUI-16: a failed Delivered toggle is swallowed (current gap)', async () => {
setProcedure('admin.order.updateDelivered', { mode: 'error', error: new Error('boom') }) setProcedure('admin.order.updateDelivered', { mode: 'error', error: new Error('boom') })
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-delivered-11')) fireEvent.press(view.getByTestId('order-delivered-11'))
await waitFor(() =>
expect(procedureMutationCalls('admin.order.updateDelivered')).toHaveLength(1)
)
await flush(2) await flush(2)
expect(procedureMutationCalls('admin.order.updateDelivered')).toHaveLength(1)
expect(alertSpy).not.toHaveBeenCalled() expect(alertSpy).not.toHaveBeenCalled()
}) })
it('AORDUI-17: tapping the card opens the order details route', () => { it('AORDUI-17: tapping the card opens the order details route', async () => {
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-card-11')) fireEvent.press(view.getByTestId('order-card-11'))
@ -249,9 +286,9 @@ describe('Orders list (AORDUI-01..36)', () => {
) )
}) })
it('AORDUI-18: the items dialog lists every item and closes', () => { it('AORDUI-18: the items dialog lists every item and closes', async () => {
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-items-11')) fireEvent.press(view.getByTestId('order-items-11'))
expect(view.getByText('Order Items')).toBeTruthy() expect(view.getByText('Order Items')).toBeTruthy()
@ -265,9 +302,9 @@ describe('Orders list (AORDUI-01..36)', () => {
expect(view.queryByText('Order Items')).toBeNull() expect(view.queryByText('Order Items')).toBeNull()
}) })
it('AORDUI-19: the row menu opens OrderOptionsMenu', () => { it('AORDUI-19: the row menu opens OrderOptionsMenu', async () => {
setOrders([ORDER_1]) setOrders([ORDER_1])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-menu-11')) fireEvent.press(view.getByTestId('order-menu-11'))
@ -277,142 +314,148 @@ describe('Orders list (AORDUI-01..36)', () => {
it('AORDUI-20: saving Admin Notes calls updateNotes and alerts', async () => { it('AORDUI-20: saving Admin Notes calls updateNotes and alerts', async () => {
setOrders([{ ...ORDER_1, orderId: '11', adminNotes: 'existing note' }]) setOrders([{ ...ORDER_1, orderId: '11', adminNotes: 'existing note' }])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-menu-11')) fireEvent.press(view.getByTestId('order-menu-11'))
fireEvent.press(view.getByTestId('order-menu-admin-notes')) fireEvent.press(view.getByTestId('order-menu-admin-notes'))
fireEvent.changeText(view.getByPlaceholderText('Enter admin notes...'), 'New note') fireEvent.changeText(view.getByPlaceholderText('Enter admin notes...'), 'New note')
fireEvent.press(view.getByText('Save')) fireEvent.press(view.getByText('Save'))
await flush(2) await waitFor(() =>
expect(lastMutationInput('admin.order.updateNotes')).toEqual({ expect(lastMutationInput('admin.order.updateNotes')).toEqual({
orderId: 11, orderId: 11,
adminNotes: 'New note', adminNotes: 'New note',
}) })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Notes updated successfully') expect(alertSpy).toHaveBeenCalledWith('Success', 'Notes updated successfully')
)
}) })
it('AORDUI-21: a failed Admin Notes save shows an alert', async () => { it('AORDUI-21: a failed Admin Notes save shows an alert', async () => {
setProcedure('admin.order.updateNotes', { mode: 'error', error: new Error('boom') }) setProcedure('admin.order.updateNotes', { mode: 'error', error: new Error('boom') })
setOrders([{ ...ORDER_1, orderId: '11', adminNotes: 'existing note' }]) setOrders([{ ...ORDER_1, orderId: '11', adminNotes: 'existing note' }])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-menu-11')) fireEvent.press(view.getByTestId('order-menu-11'))
fireEvent.press(view.getByTestId('order-menu-admin-notes')) fireEvent.press(view.getByTestId('order-menu-admin-notes'))
fireEvent.press(view.getByText('Save')) fireEvent.press(view.getByText('Save'))
await flush(2) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'boom'))
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
}) })
it('AORDUI-22: empty Admin Notes are saved as an empty string', async () => { it('AORDUI-22: empty Admin Notes are saved as an empty string', async () => {
setOrders([{ ...ORDER_1, orderId: '11', adminNotes: 'existing note' }]) setOrders([{ ...ORDER_1, orderId: '11', adminNotes: 'existing note' }])
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('order-menu-11')) fireEvent.press(view.getByTestId('order-menu-11'))
fireEvent.press(view.getByTestId('order-menu-admin-notes')) fireEvent.press(view.getByTestId('order-menu-admin-notes'))
fireEvent.changeText(view.getByPlaceholderText('Enter admin notes...'), '') fireEvent.changeText(view.getByPlaceholderText('Enter admin notes...'), '')
fireEvent.press(view.getByText('Save')) fireEvent.press(view.getByText('Save'))
await flush(2) await waitFor(() =>
expect(lastMutationInput('admin.order.updateNotes')).toEqual({ expect(lastMutationInput('admin.order.updateNotes')).toEqual({
orderId: 11, orderId: 11,
adminNotes: '', adminNotes: '',
}) })
)
}) })
it('AORDUI-23: choosing a slot filters the query by slotId', () => { it('AORDUI-23: choosing a slot filters the query by slotId', async () => {
const view = renderOrders() const view = await renderOrders()
fireEvent.press(view.getByTestId('orders-slot-dropdown')) fireEvent.press(view.getByTestId('orders-slot-dropdown'))
fireEvent.press(view.getByTestId('orders-slot-dropdown-option-1849')) fireEvent.press(view.getByTestId('orders-slot-dropdown-option-1849'))
expect(lastOrdersInput()).toMatchObject({ slotId: 1849 }) await expectOrdersInput(view, { slotId: 1849 })
}) })
it('AORDUI-24: the Flash shortcut sets the flash filter and resets the others', () => { it('AORDUI-24: the Flash shortcut sets the flash filter and resets the others', async () => {
const view = renderOrders() const view = await renderOrders()
openFilters(view) openFilters(view)
fireEvent.press(view.getByTestId('filter-packaged')) fireEvent.press(view.getByTestId('filter-packaged'))
await expectFiltersVisible(view)
closeTopDialog(view) closeTopDialog(view)
fireEvent.press(view.getByTestId('orders-slot-dropdown')) fireEvent.press(view.getByTestId('orders-slot-dropdown'))
fireEvent.press(view.getByTestId('orders-slot-dropdown-option-flash')) fireEvent.press(view.getByTestId('orders-slot-dropdown-option-flash'))
expect(lastOrdersInput()).toMatchObject({ await expectOrdersInput(view, {
slotId: null, slotId: null,
packagedFilter: 'all', packagedFilter: 'all',
deliveredFilter: 'all', deliveredFilter: 'all',
cancellationFilter: 'all', cancellationFilter: 'all',
flashDeliveryFilter: 'flash', flashDeliveryFilter: 'flash',
}) })
expect(view.getByText('5 Flash delivery orders')).toBeTruthy() expect(await view.findByText('5 Flash delivery orders')).toBeTruthy()
}) })
it('AORDUI-25: the packaged filter cycles all/packaged/not_packaged', () => { it('AORDUI-25: the packaged filter cycles all/packaged/not_packaged', async () => {
const view = renderOrders() const view = await renderOrders()
openFilters(view) openFilters(view)
expect(lastOrdersInput()).toMatchObject({ packagedFilter: 'all' }) expect(lastOrdersInput()).toMatchObject({ packagedFilter: 'all' })
fireEvent.press(view.getByTestId('filter-packaged')) fireEvent.press(view.getByTestId('filter-packaged'))
expect(lastOrdersInput()).toMatchObject({ packagedFilter: 'packaged' }) await expectOrdersInput(view, { packagedFilter: 'packaged' })
await expectFiltersVisible(view)
fireEvent.press(view.getByTestId('filter-packaged')) fireEvent.press(view.getByTestId('filter-packaged'))
expect(lastOrdersInput()).toMatchObject({ packagedFilter: 'all' }) await expectOrdersInput(view, { packagedFilter: 'all' })
fireEvent.press(view.getByTestId('filter-not-packaged')) fireEvent.press(view.getByTestId('filter-not-packaged'))
expect(lastOrdersInput()).toMatchObject({ packagedFilter: 'not_packaged' }) await expectOrdersInput(view, { packagedFilter: 'not_packaged' })
}) })
it('AORDUI-26: the delivered filter cycles all/delivered/not_delivered', () => { it('AORDUI-26: the delivered filter cycles all/delivered/not_delivered', async () => {
const view = renderOrders() const view = await renderOrders()
openFilters(view) openFilters(view)
fireEvent.press(view.getByTestId('filter-delivered')) fireEvent.press(view.getByTestId('filter-delivered'))
expect(lastOrdersInput()).toMatchObject({ deliveredFilter: 'delivered' }) await expectOrdersInput(view, { deliveredFilter: 'delivered' })
await expectFiltersVisible(view)
fireEvent.press(view.getByTestId('filter-delivered')) fireEvent.press(view.getByTestId('filter-delivered'))
expect(lastOrdersInput()).toMatchObject({ deliveredFilter: 'all' }) await expectOrdersInput(view, { deliveredFilter: 'all' })
fireEvent.press(view.getByTestId('filter-not-delivered')) fireEvent.press(view.getByTestId('filter-not-delivered'))
expect(lastOrdersInput()).toMatchObject({ deliveredFilter: 'not_delivered' }) await expectOrdersInput(view, { deliveredFilter: 'not_delivered' })
}) })
it('AORDUI-27: the cancellation filter cycles all/cancelled/not_cancelled', () => { it('AORDUI-27: the cancellation filter cycles all/cancelled/not_cancelled', async () => {
const view = renderOrders() const view = await renderOrders()
openFilters(view) openFilters(view)
fireEvent.press(view.getByTestId('filter-cancelled')) fireEvent.press(view.getByTestId('filter-cancelled'))
expect(lastOrdersInput()).toMatchObject({ cancellationFilter: 'cancelled' }) await expectOrdersInput(view, { cancellationFilter: 'cancelled' })
await expectFiltersVisible(view)
fireEvent.press(view.getByTestId('filter-cancelled')) fireEvent.press(view.getByTestId('filter-cancelled'))
expect(lastOrdersInput()).toMatchObject({ cancellationFilter: 'all' }) await expectOrdersInput(view, { cancellationFilter: 'all' })
fireEvent.press(view.getByTestId('filter-not-cancelled')) fireEvent.press(view.getByTestId('filter-not-cancelled'))
expect(lastOrdersInput()).toMatchObject({ cancellationFilter: 'not_cancelled' }) await expectOrdersInput(view, { cancellationFilter: 'not_cancelled' })
}) })
it('AORDUI-28: the delivery-type filter cycles all/flash/regular', () => { it('AORDUI-28: the delivery-type filter cycles all/flash/regular', async () => {
const view = renderOrders() const view = await renderOrders()
openFilters(view) openFilters(view)
fireEvent.press(view.getByTestId('filter-flash')) fireEvent.press(view.getByTestId('filter-flash'))
expect(lastOrdersInput()).toMatchObject({ flashDeliveryFilter: 'flash' }) await expectOrdersInput(view, { flashDeliveryFilter: 'flash' })
await expectFiltersVisible(view)
fireEvent.press(view.getByTestId('filter-flash')) fireEvent.press(view.getByTestId('filter-flash'))
expect(lastOrdersInput()).toMatchObject({ flashDeliveryFilter: 'all' }) await expectOrdersInput(view, { flashDeliveryFilter: 'all' })
fireEvent.press(view.getByTestId('filter-regular')) fireEvent.press(view.getByTestId('filter-regular'))
expect(lastOrdersInput()).toMatchObject({ flashDeliveryFilter: 'regular' }) await expectOrdersInput(view, { flashDeliveryFilter: 'regular' })
}) })
it('AORDUI-29: closing and reopening the filter dialog keeps the selections', () => { it('AORDUI-29: closing and reopening the filter dialog keeps the selections', async () => {
const view = renderOrders() const view = await renderOrders()
openFilters(view) openFilters(view)
fireEvent.press(view.getByTestId('filter-packaged')) fireEvent.press(view.getByTestId('filter-packaged'))
await expectFiltersVisible(view)
closeTopDialog(view) closeTopDialog(view)
openFilters(view) openFilters(view)
@ -420,29 +463,31 @@ describe('Orders list (AORDUI-01..36)', () => {
expect(view.getByTestId('filter-packaged').props.accessibilityState.checked).toBe(true) expect(view.getByTestId('filter-packaged').props.accessibilityState.checked).toBe(true)
}) })
it('AORDUI-30: end-of-list only fetches when another page exists (none in the mock)', () => { it('AORDUI-30: end-of-list only fetches when another page exists (none in the mock)', async () => {
const view = renderOrders() const view = await renderOrders()
const list = view.UNSAFE_getByType(FlatList) const list = view.UNSAFE_getByType(FlatList)
expect(typeof list.props.onEndReached).toBe('function') expect(typeof list.props.onEndReached).toBe('function')
await act(async () => {
list.props.onEndReached() list.props.onEndReached()
})
await flush(2)
expect(view.queryByText('Loading more...')).toBeNull() expect(view.queryByText('Loading more...')).toBeNull()
}) })
it('AORDUI-31: the list exposes a pull-to-refresh handler', () => { it('AORDUI-31: the list exposes a pull-to-refresh handler', async () => {
const view = renderOrders() const view = await renderOrders()
const refreshControl = view.UNSAFE_getByType(RefreshControl) const refreshControl = view.UNSAFE_getByType(RefreshControl)
expect(typeof refreshControl.props.onRefresh).toBe('function') expect(typeof refreshControl.props.onRefresh).toBe('function')
fireEvent(refreshControl, 'refresh') fireEvent(refreshControl, 'refresh')
expect(view.getAllByText('Test User').length).toBeGreaterThan(0) await waitFor(() => expect(view.getAllByText('Test User').length).toBeGreaterThan(0))
}) })
it('AORDUI-32: the getAll query is mounted for the refresh/focus fetcher', async () => { it('AORDUI-32: the getAll query is mounted for the refresh/focus fetcher', async () => {
const view = renderOrders() const view = await renderOrders()
await flush()
// useFocusEffect is mount-only in the harness, so the second-focus refetch // useFocusEffect is mount-only in the harness, so the second-focus refetch
// cannot be observed; assert the fetcher's query is mounted instead. // cannot be observed; assert the fetcher's query is mounted instead.
@ -450,34 +495,43 @@ describe('Orders list (AORDUI-01..36)', () => {
expect(view.getAllByText('Test User').length).toBeGreaterThan(0) expect(view.getAllByText('Test User').length).toBeGreaterThan(0)
}) })
it('AORDUI-33: duplicate pages are appended without dedupe (current behaviour)', () => { it('AORDUI-33: duplicate pages are appended without dedupe (current behaviour)', async () => {
// A second page is only requested when the first page reports a cursor; the
// real client then appends the duplicate page verbatim.
setProcedure('admin.order.getAll', { setProcedure('admin.order.getAll', {
data: { pages: [{ orders: [ORDER_1] }, { orders: [ORDER_1] }] }, data: { orders: [ORDER_1], nextCursor: 'page-2' },
}) })
const view = renderOrders() const view = await renderOrders()
expect(view.getAllByText('Test User')).toHaveLength(2) const list = view.UNSAFE_getByType(FlatList)
await act(async () => {
list.props.onEndReached()
})
await flush(2)
expect(await view.findAllByText('Test User')).toHaveLength(2)
}) })
it('AORDUI-34: the URL filter=flash selects the flash filter initially', async () => { it('AORDUI-34: the URL filter=flash selects the flash filter initially', async () => {
__setParams({ filter: 'flash' }) __setParams({ filter: 'flash' })
const view = renderOrders() const view = await renderOrders()
await flush(2)
await waitFor(() =>
expect(lastOrdersInput()).toMatchObject({ flashDeliveryFilter: 'flash' }) expect(lastOrdersInput()).toMatchObject({ flashDeliveryFilter: 'flash' })
expect(view.getByText('5 Flash delivery orders')).toBeTruthy() )
expect(await view.findByText('5 Flash delivery orders')).toBeTruthy()
}) })
it('AORDUI-35: status text is capitalised only in the cancelled banner', () => { it('AORDUI-35: status text is capitalised only in the cancelled banner', async () => {
setOrders([ORDER_CANCELLED]) setOrders([ORDER_CANCELLED])
const view = renderOrders() const view = await renderOrders()
expect(view.getByText('CANCELLED')).toBeTruthy() expect(view.getByText('CANCELLED')).toBeTruthy()
expect(view.queryByText('pending')).toBeNull() expect(view.queryByText('pending')).toBeNull()
expect(view.queryByText('cancelled')).toBeNull() expect(view.queryByText('cancelled')).toBeNull()
}) })
it('AORDUI-36: long addresses and product names are truncated without crashing', () => { it('AORDUI-36: long addresses and product names are truncated without crashing', async () => {
const longAddress = const longAddress =
'12 Very Long Street Name, Apartment 4B, Near The Big Market, Mahabubnagar, Telangana' '12 Very Long Street Name, Apartment 4B, Near The Big Market, Mahabubnagar, Telangana'
const longName = 'Extremely Long Chicken Breast Product Name For Truncation' const longName = 'Extremely Long Chicken Breast Product Name For Truncation'
@ -492,7 +546,7 @@ describe('Orders list (AORDUI-01..36)', () => {
], ],
} }
setOrders([order]) setOrders([order])
const view = renderOrders() const view = await renderOrders()
expect(view.getByText(longAddress)).toBeTruthy() expect(view.getByText(longAddress)).toBeTruthy()

View file

@ -5,7 +5,7 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import DraggableFlatList from 'react-native-draggable-flatlist' import DraggableFlatList from 'react-native-draggable-flatlist'
import PopularItems from '@/app/(drawer)/dashboard/customize-app/popular-items' import PopularItems from '@/app/(drawer)/dashboard/customize-app/popular-items'
@ -180,6 +180,7 @@ describe('Popular items (APOP-01..16)', () => {
expect(view.getByText('Choose products...')).toBeTruthy() expect(view.getByText('Choose products...')).toBeTruthy()
fireEvent.press(view.getByText('Choose products...')) fireEvent.press(view.getByText('Choose products...'))
await flush()
expect(view.getByText('Chicken Breast - ₹215')).toBeTruthy() expect(view.getByText('Chicken Breast - ₹215')).toBeTruthy()
expect(view.getByText('Cucumber - ₹15')).toBeTruthy() expect(view.getByText('Cucumber - ₹15')).toBeTruthy()
}) })
@ -191,6 +192,7 @@ describe('Popular items (APOP-01..16)', () => {
expect(disabled(view, 'Add Products')).toBe(true) expect(disabled(view, 'Add Products')).toBe(true)
fireEvent.press(view.getByText('Choose products...')) fireEvent.press(view.getByText('Choose products...'))
await flush()
fireEvent.press(view.getByText('Chicken Breast - ₹215')) fireEvent.press(view.getByText('Chicken Breast - ₹215'))
fireEvent.press(view.getByText('Done')) fireEvent.press(view.getByText('Done'))
@ -202,6 +204,7 @@ describe('Popular items (APOP-01..16)', () => {
openAddDialog(view) openAddDialog(view)
fireEvent.press(view.getByText('Choose products...')) fireEvent.press(view.getByText('Choose products...'))
await flush()
fireEvent.press(view.getByText('Chicken Breast - ₹215')) fireEvent.press(view.getByText('Chicken Breast - ₹215'))
fireEvent.press(view.getByText('Cucumber - ₹15')) fireEvent.press(view.getByText('Cucumber - ₹15'))
fireEvent.press(view.getByText('Done')) fireEvent.press(view.getByText('Done'))
@ -232,6 +235,7 @@ describe('Popular items (APOP-01..16)', () => {
openAddDialog(view) openAddDialog(view)
fireEvent.press(view.getByText('Choose products...')) fireEvent.press(view.getByText('Choose products...'))
await flush()
fireEvent.press(view.getByText('Chicken Breast - ₹215')) fireEvent.press(view.getByText('Chicken Breast - ₹215'))
fireEvent.press(view.getByText('Done')) fireEvent.press(view.getByText('Done'))
fireEvent.press(view.getByText('Add 1 Product')) fireEvent.press(view.getByText('Add 1 Product'))
@ -278,10 +282,12 @@ describe('Popular items (APOP-01..16)', () => {
fireEvent.press(view.getByText('Save')) fireEvent.press(view.getByText('Save'))
await flush() await flush()
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Error', 'Error',
'Failed to update popular items. Please try again.' 'Failed to update popular items. Please try again.'
) )
)
}) })
it('APOP-15: the picker is SKU-based while the list/payload is product-id based', async () => { it('APOP-15: the picker is SKU-based while the list/payload is product-id based', async () => {
@ -289,6 +295,7 @@ describe('Popular items (APOP-01..16)', () => {
openAddDialog(view) openAddDialog(view)
fireEvent.press(view.getByText('Choose products...')) fireEvent.press(view.getByText('Choose products...'))
await flush()
// Options come from getAllSkusSummary: SKU ids 11/13. // Options come from getAllSkusSummary: SKU ids 11/13.
expect(procedureQueryCalls('common.product.getAllSkusSummary').length).toBeGreaterThan(0) expect(procedureQueryCalls('common.product.getAllSkusSummary').length).toBeGreaterThan(0)

View file

@ -5,21 +5,21 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, Image, Modal } from 'react-native' import { Alert, Image, Modal } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import PricesOverview from '@/app/(drawer)/dashboard/prices-overview/index' import PricesOverview from '@/app/(drawer)/dashboard/prices-overview/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client' import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { PRODUCTS_RESPONSE, STORES, P_CHICKEN, P_NO_IMAGE } from '../fixtures' import { PRODUCTS_RESPONSE, STORES, P_CHICKEN, P_NO_IMAGE } from '../fixtures'
type View = ReturnType<typeof renderWithProviders> async function renderPrices() {
return renderAndFlush(<PricesOverview />, { auth: 'in' })
function renderPrices() {
return renderWithProviders(<PricesOverview />, { auth: 'in' })
} }
type View = Awaited<ReturnType<typeof renderPrices>>
function openEdit(view: View, skuId: number) { function openEdit(view: View, skuId: number) {
fireEvent.press(view.getByTestId(`edit-sku-price-${skuId}`)) fireEvent.press(view.getByTestId(`edit-sku-price-${skuId}`))
} }
@ -40,8 +40,9 @@ function submitDialog(view: View) {
fireEvent.press(view.getByText('Update Price')) fireEvent.press(view.getByText('Update Price'))
} }
function pressSave(view: View) { async function pressSave(view: View) {
fireEvent.press(view.getByTestId('save-prices-button')) fireEvent.press(view.getByTestId('save-prices-button'))
await flush(3)
} }
describe('Prices overview (APRICE-01..30)', () => { describe('Prices overview (APRICE-01..30)', () => {
@ -54,15 +55,15 @@ describe('Prices overview (APRICE-01..30)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('APRICE-01: shows the loading copy while products or stores load', () => { it('APRICE-01: shows the loading copy while products or stores load', async () => {
setProcedure('admin.product.getProducts', { mode: 'pending' }) setProcedure('admin.product.getProducts', { mode: 'pending' })
const view = renderPrices() const view = await renderPrices()
expect(view.getByText('Loading...')).toBeTruthy() expect(view.getByText('Loading...')).toBeTruthy()
}) })
it('APRICE-02: flattens SKUs and shows product name, unit and prices', () => { it('APRICE-02: flattens SKUs and shows product name, unit and prices', async () => {
const view = renderPrices() const view = await renderPrices()
expect(view.getAllByText('Chicken Breast').length).toBe(2) expect(view.getAllByText('Chicken Breast').length).toBe(2)
expect(view.getByText('Cucumber')).toBeTruthy() expect(view.getByText('Cucumber')).toBeTruthy()
@ -73,7 +74,7 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(view.getByText('1kg')).toBeTruthy() expect(view.getByText('1kg')).toBeTruthy()
}) })
it('APRICE-03: a product with no SKUs is omitted from the list', () => { it('APRICE-03: a product with no SKUs is omitted from the list', async () => {
setProcedure('admin.product.getProducts', { setProcedure('admin.product.getProducts', {
data: { data: {
products: [ products: [
@ -88,33 +89,33 @@ describe('Prices overview (APRICE-01..30)', () => {
count: 2, count: 2,
}, },
}) })
const view = renderPrices() const view = await renderPrices()
expect(view.getAllByText('Chicken Breast').length).toBeGreaterThanOrEqual(1) expect(view.getAllByText('Chicken Breast').length).toBeGreaterThanOrEqual(1)
expect(view.queryByText('Ghost Product')).toBeNull() expect(view.queryByText('Ghost Product')).toBeNull()
}) })
it('APRICE-04: a SKU without images uses the placeholder URI', () => { it('APRICE-04: a SKU without images uses the placeholder URI', async () => {
setProcedure('admin.product.getProducts', { setProcedure('admin.product.getProducts', {
data: { products: [P_NO_IMAGE], count: 1 }, data: { products: [P_NO_IMAGE], count: 1 },
}) })
const view = renderPrices() const view = await renderPrices()
const images = view.UNSAFE_getAllByType(Image) const images = view.UNSAFE_getAllByType(Image)
const sources = images.map((image) => image.props.source?.uri) const sources = images.map((image) => image.props.source?.uri)
expect(sources).toContain('https://via.placeholder.com/32x32?text=No+Image') expect(sources).toContain('https://via.placeholder.com/32x32?text=No+Image')
}) })
it('APRICE-05: missing market and flash prices render as N/A', () => { it('APRICE-05: missing market and flash prices render as N/A', async () => {
setProcedure('admin.product.getProducts', { setProcedure('admin.product.getProducts', {
data: { products: [P_NO_IMAGE], count: 1 }, data: { products: [P_NO_IMAGE], count: 1 },
}) })
const view = renderPrices() const view = await renderPrices()
expect(view.getAllByText('N/A')).toHaveLength(2) expect(view.getAllByText('N/A')).toHaveLength(2)
}) })
it('APRICE-06: long product names are truncated to 20 characters', () => { it('APRICE-06: long product names are truncated to 20 characters', async () => {
const longName = 'This Is A Very Long Product Name' const longName = 'This Is A Very Long Product Name'
setProcedure('admin.product.getProducts', { setProcedure('admin.product.getProducts', {
data: { data: {
@ -122,20 +123,20 @@ describe('Prices overview (APRICE-01..30)', () => {
count: 1, count: 1,
}, },
}) })
const view = renderPrices() const view = await renderPrices()
expect(view.getAllByText('This Is A Very Long ...').length).toBeGreaterThanOrEqual(1) expect(view.getAllByText('This Is A Very Long ...').length).toBeGreaterThanOrEqual(1)
expect(view.queryByText(longName)).toBeNull() expect(view.queryByText(longName)).toBeNull()
}) })
it('APRICE-07: all stores are selected by default in the store filter', () => { it('APRICE-07: all stores are selected by default in the store filter', async () => {
const view = renderPrices() const view = await renderPrices()
expect(view.getByText('Freshyo Central, The Freshyo Meat House')).toBeTruthy() expect(view.getByText('Freshyo Central, The Freshyo Meat House')).toBeTruthy()
}) })
it('APRICE-08: deselecting a store hides its SKUs', () => { it('APRICE-08: deselecting a store hides its SKUs', async () => {
const view = renderPrices() const view = await renderPrices()
fireEvent.press(view.getByTestId('store-filter-dropdown')) fireEvent.press(view.getByTestId('store-filter-dropdown'))
fireEvent.press(view.getByTestId('store-filter-dropdown-option-2')) fireEvent.press(view.getByTestId('store-filter-dropdown-option-2'))
@ -145,14 +146,14 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(view.queryByText('Global Paneer')).toBeNull() expect(view.queryByText('Global Paneer')).toBeNull()
}) })
it('APRICE-09: a store filter with no matching products yields an empty list', () => { it('APRICE-09: a store filter with no matching products yields an empty list', async () => {
setProcedure('admin.store.getStores', { setProcedure('admin.store.getStores', {
data: { data: {
stores: [...STORES, { id: 3, name: 'Empty Store', isGlobal: false, productCount: 0, createdAt: null }], stores: [...STORES, { id: 3, name: 'Empty Store', isGlobal: false, productCount: 0, createdAt: null }],
count: 3, count: 3,
}, },
}) })
const view = renderPrices() const view = await renderPrices()
fireEvent.press(view.getByTestId('store-filter-dropdown')) fireEvent.press(view.getByTestId('store-filter-dropdown'))
fireEvent.press(view.getByTestId('store-filter-dropdown-option-1')) fireEvent.press(view.getByTestId('store-filter-dropdown-option-1'))
@ -164,8 +165,8 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(view.getByText('Save (0)')).toBeTruthy() expect(view.getByText('Save (0)')).toBeTruthy()
}) })
it('APRICE-10: the edit dialog is prefilled with the SKU prices', () => { it('APRICE-10: the edit dialog is prefilled with the SKU prices', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
@ -174,8 +175,8 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(view.getByPlaceholderText('Enter flash price').props.value).toBe('') expect(view.getByPlaceholderText('Enter flash price').props.value).toBe('')
}) })
it('APRICE-11: an empty, zero or negative price is rejected', () => { it('APRICE-11: an empty, zero or negative price is rejected', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { price: '' }) fillDialog(view, { price: '' })
@ -193,8 +194,8 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(view.getByText('Save (0)')).toBeTruthy() expect(view.getByText('Save (0)')).toBeTruthy()
}) })
it('APRICE-12: an invalid market price is rejected', () => { it('APRICE-12: an invalid market price is rejected', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { market: 'abc' }) fillDialog(view, { market: 'abc' })
@ -203,8 +204,8 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(alertSpy).toHaveBeenLastCalledWith('Error', 'Please enter a valid market price') expect(alertSpy).toHaveBeenLastCalledWith('Error', 'Please enter a valid market price')
}) })
it('APRICE-13: an invalid flash price is rejected', () => { it('APRICE-13: an invalid flash price is rejected', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { flash: '-1' }) fillDialog(view, { flash: '-1' })
@ -213,35 +214,35 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(alertSpy).toHaveBeenLastCalledWith('Error', 'Please enter a valid flash price') expect(alertSpy).toHaveBeenLastCalledWith('Error', 'Please enter a valid flash price')
}) })
it('APRICE-14: empty market/flash fields become null pending values', () => { it('APRICE-14: empty market/flash fields become null pending values', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { market: '', flash: '' }) fillDialog(view, { market: '', flash: '' })
submitDialog(view) submitDialog(view)
pressSave(view) await pressSave(view)
expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({ expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({
updates: [{ skuId: 13, marketPrice: null, flashPrice: null }], updates: [{ skuId: 13, marketPrice: null, flashPrice: null }],
}) })
}) })
it('APRICE-15: unchanged values still create a pending change object', () => { it('APRICE-15: unchanged values still create a pending change object', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
submitDialog(view) submitDialog(view)
expect(view.getByText('Save (1)')).toBeTruthy() expect(view.getByText('Save (1)')).toBeTruthy()
pressSave(view) await pressSave(view)
expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({ expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({
updates: [{ skuId: 13, flashPrice: null }], updates: [{ skuId: 13, flashPrice: null }],
}) })
}) })
it('APRICE-16: a pending change shows the green check indicator', () => { it('APRICE-16: a pending change shows the green check indicator', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { price: '18' }) fillDialog(view, { price: '18' })
@ -253,8 +254,8 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(checkIcons.length).toBeGreaterThan(0) expect(checkIcons.length).toBeGreaterThan(0)
}) })
it('APRICE-17: the save button shows the pending change count', () => { it('APRICE-17: the save button shows the pending change count', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 11) openEdit(view, 11)
fillDialog(view, { price: '300' }) fillDialog(view, { price: '300' })
@ -267,30 +268,30 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(view.getByText('Save (2)')).toBeTruthy() expect(view.getByText('Save (2)')).toBeTruthy()
}) })
it('APRICE-18: save is disabled when there are no changes', () => { it('APRICE-18: save is disabled when there are no changes', async () => {
const view = renderPrices() const view = await renderPrices()
expect(view.getByText('Save (0)')).toBeTruthy() expect(view.getByText('Save (0)')).toBeTruthy()
pressSave(view) await pressSave(view)
expect(procedureMutationCalls('admin.product.updateProductPrices')).toHaveLength(0) expect(procedureMutationCalls('admin.product.updateProductPrices')).toHaveLength(0)
}) })
it('APRICE-19: saving sends updateProductPrices with the SKU updates', () => { it('APRICE-19: saving sends updateProductPrices with the SKU updates', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 11) openEdit(view, 11)
fillDialog(view, { price: '300', market: '250' }) fillDialog(view, { price: '300', market: '250' })
submitDialog(view) submitDialog(view)
pressSave(view) await pressSave(view)
expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({ expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({
updates: [{ skuId: 11, price: 300, marketPrice: 250, flashPrice: null }], updates: [{ skuId: 11, price: 300, marketPrice: 250, flashPrice: null }],
}) })
}) })
it('APRICE-20: multiple SKUs produce one update entry per SKU', () => { it('APRICE-20: multiple SKUs produce one update entry per SKU', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 11) openEdit(view, 11)
fillDialog(view, { price: '300' }) fillDialog(view, { price: '300' })
@ -298,18 +299,18 @@ describe('Prices overview (APRICE-01..30)', () => {
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { price: '20' }) fillDialog(view, { price: '20' })
submitDialog(view) submitDialog(view)
pressSave(view) await pressSave(view)
const input = lastMutationInput('admin.product.updateProductPrices') const input = lastMutationInput('admin.product.updateProductPrices')
expect(input.updates).toHaveLength(2) expect(input.updates).toHaveLength(2)
expect(input.updates.map((update: any) => update.skuId)).toEqual([11, 13]) expect(input.updates.map((update: any) => update.skuId)).toEqual([11, 13])
}) })
it('APRICE-21: toggling only the flash checkbox sends isFlashAvailable', () => { it('APRICE-21: toggling only the flash checkbox sends isFlashAvailable', async () => {
const view = renderPrices() const view = await renderPrices()
fireEvent.press(view.getByTestId('flash-checkbox-11')) fireEvent.press(view.getByTestId('flash-checkbox-11'))
pressSave(view) await pressSave(view)
expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({ expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({
updates: [{ skuId: 11, isFlashAvailable: true }], updates: [{ skuId: 11, isFlashAvailable: true }],
@ -318,30 +319,30 @@ describe('Prices overview (APRICE-01..30)', () => {
it('APRICE-22: a pending save disables the save action and keeps the spinner', async () => { it('APRICE-22: a pending save disables the save action and keeps the spinner', async () => {
setProcedure('admin.product.updateProductPrices', { mode: 'pending' }) setProcedure('admin.product.updateProductPrices', { mode: 'pending' })
const view = renderPrices() const view = await renderPrices()
fireEvent.press(view.getByTestId('flash-checkbox-11')) fireEvent.press(view.getByTestId('flash-checkbox-11'))
pressSave(view) await pressSave(view)
await flush() await flush()
expect(view.getByText('Save (1)')).toBeTruthy() expect(view.getByText('Save (1)')).toBeTruthy()
pressSave(view) await pressSave(view)
await flush() await flush()
expect(procedureMutationCalls('admin.product.updateProductPrices')).toHaveLength(1) expect(procedureMutationCalls('admin.product.updateProductPrices')).toHaveLength(1)
}) })
it('APRICE-23: a successful save clears pending changes, refetches and alerts', async () => { it('APRICE-23: a successful save clears pending changes, refetches and alerts', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { price: '18' }) fillDialog(view, { price: '18' })
submitDialog(view) submitDialog(view)
pressSave(view) await pressSave(view)
await flush() await flush()
expect(view.getByText('Save (0)')).toBeTruthy() expect(view.getByText('Save (0)')).toBeTruthy()
expect(alertSpy).toHaveBeenCalledWith('Success', 'Prices updated successfully') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Prices updated successfully'))
}) })
it('APRICE-24: a failed mutation alerts with the error message', async () => { it('APRICE-24: a failed mutation alerts with the error message', async () => {
@ -349,19 +350,19 @@ describe('Prices overview (APRICE-01..30)', () => {
mode: 'error', mode: 'error',
error: new Error('boom'), error: new Error('boom'),
}) })
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { price: '18' }) fillDialog(view, { price: '18' })
submitDialog(view) submitDialog(view)
pressSave(view) await pressSave(view)
await flush() await flush()
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to update prices: boom') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to update prices: boom'))
}) })
it('APRICE-25: closing the edit dialog resets its temporary fields', () => { it('APRICE-25: closing the edit dialog resets its temporary fields', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { price: '999' }) fillDialog(view, { price: '999' })
@ -373,8 +374,8 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(view.getByPlaceholderText('Enter price').props.value).toBe('15') expect(view.getByPlaceholderText('Enter price').props.value).toBe('15')
}) })
it('APRICE-26: the options menu navigates to rebalance orders', () => { it('APRICE-26: the options menu navigates to rebalance orders', async () => {
const view = renderPrices() const view = await renderPrices()
fireEvent.press(view.getByTestId('prices-options-button')) fireEvent.press(view.getByTestId('prices-options-button'))
fireEvent.press(view.getByText('Re-Balance Orders')) fireEvent.press(view.getByText('Re-Balance Orders'))
@ -382,8 +383,8 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/rebalance-orders') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/rebalance-orders')
}) })
it('APRICE-27: pending changes are preserved across multiple dialogs', () => { it('APRICE-27: pending changes are preserved across multiple dialogs', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 11) openEdit(view, 11)
fillDialog(view, { price: '300' }) fillDialog(view, { price: '300' })
@ -391,7 +392,7 @@ describe('Prices overview (APRICE-01..30)', () => {
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { price: '20' }) fillDialog(view, { price: '20' })
submitDialog(view) submitDialog(view)
pressSave(view) await pressSave(view)
const input = lastMutationInput('admin.product.updateProductPrices') const input = lastMutationInput('admin.product.updateProductPrices')
expect(input.updates).toEqual([ expect(input.updates).toEqual([
@ -400,8 +401,8 @@ describe('Prices overview (APRICE-01..30)', () => {
]) ])
}) })
it('APRICE-28: switching the store filter keeps pending changes', () => { it('APRICE-28: switching the store filter keeps pending changes', async () => {
const view = renderPrices() const view = await renderPrices()
fireEvent.press(view.getByTestId('flash-checkbox-11')) fireEvent.press(view.getByTestId('flash-checkbox-11'))
fireEvent.press(view.getByTestId('store-filter-dropdown')) fireEvent.press(view.getByTestId('store-filter-dropdown'))
@ -411,32 +412,32 @@ describe('Prices overview (APRICE-01..30)', () => {
expect(view.queryByText('Chicken Breast')).toBeNull() expect(view.queryByText('Chicken Breast')).toBeNull()
expect(view.getByText('Save (1)')).toBeTruthy() expect(view.getByText('Save (1)')).toBeTruthy()
pressSave(view) await pressSave(view)
expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({ expect(lastMutationInput('admin.product.updateProductPrices')).toEqual({
updates: [{ skuId: 11, isFlashAvailable: true }], updates: [{ skuId: 11, isFlashAvailable: true }],
}) })
}) })
it('APRICE-29: the payload uses the SKU id, not the product id (regression)', () => { it('APRICE-29: the payload uses the SKU id, not the product id (regression)', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 11) openEdit(view, 11)
fillDialog(view, { price: '300' }) fillDialog(view, { price: '300' })
submitDialog(view) submitDialog(view)
pressSave(view) await pressSave(view)
const input = lastMutationInput('admin.product.updateProductPrices') const input = lastMutationInput('admin.product.updateProductPrices')
expect(input.updates[0].skuId).toBe(11) expect(input.updates[0].skuId).toBe(11)
expect(input.updates[0].productId).toBeUndefined() expect(input.updates[0].productId).toBeUndefined()
}) })
it('APRICE-30: an explicitly cleared market price is sent as null', () => { it('APRICE-30: an explicitly cleared market price is sent as null', async () => {
const view = renderPrices() const view = await renderPrices()
openEdit(view, 13) openEdit(view, 13)
fillDialog(view, { market: '' }) fillDialog(view, { market: '' })
submitDialog(view) submitDialog(view)
pressSave(view) await pressSave(view)
const input = lastMutationInput('admin.product.updateProductPrices') const input = lastMutationInput('admin.product.updateProductPrices')
expect(input.updates[0]).toEqual({ skuId: 13, marketPrice: null, flashPrice: null }) expect(input.updates[0]).toEqual({ skuId: 13, marketPrice: null, flashPrice: null })

View file

@ -4,25 +4,28 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
import AddProduct from '@/app/(drawer)/dashboard/products/add' import AddProduct from '@/app/(drawer)/dashboard/products/add'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
procedureMutationCalls, procedureMutationCalls,
setProcedure, setProcedure,
setRawFetchHandler,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { STORE_GLOBAL } from '../fixtures' import { STORE_GLOBAL } from '../fixtures'
function renderAdd() { async function renderAdd() {
return renderWithProviders(<AddProduct />, { auth: false }) const view = await renderAndFlush(<AddProduct />, { auth: false })
await flush(2)
return view
} }
function fillVariant( function fillVariant(
view: ReturnType<typeof renderAdd>, view: Awaited<ReturnType<typeof renderAdd>>,
index: number, index: number,
{ price, quantity }: { price: string; quantity: string } { price, quantity }: { price: string; quantity: string }
) { ) {
@ -30,17 +33,25 @@ function fillVariant(
fireEvent.changeText(view.getByTestId(`variant-${index}-attr-0-value`), quantity) fireEvent.changeText(view.getByTestId(`variant-${index}-attr-0-value`), quantity)
} }
async function submit(view: ReturnType<typeof renderAdd>) { async function submit(view: Awaited<ReturnType<typeof renderAdd>>) {
fireEvent.press(view.getByTestId('create-product-button')) fireEvent.press(view.getByTestId('create-product-button'))
await flush(2) await flush(3)
}
/** Wait for the create mutation to land, then return its input. */
async function createdPayload() {
await waitFor(() =>
expect(lastMutationInput('admin.product.createProduct')).toBeDefined()
)
return lastMutationInput('admin.product.createProduct')
} }
function mockSuccessfulUploads() { function mockSuccessfulUploads() {
;(global as any).fetch = jest.fn(async (_url: string, init?: any) => { setRawFetchHandler(async (_url, init) => {
if (init?.method === 'PUT') { if (init?.method === 'PUT') {
return { ok: true, status: 200, text: async () => '' } return { ok: true, status: 200, text: async () => '' } as any
} }
return { ok: true, status: 200, blob: async () => ({ size: 1 }) } return { ok: true, status: 200, blob: async () => ({ size: 1 }) } as any
}) })
} }
@ -59,8 +70,8 @@ describe('Add product (APADD-01..19)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('APADD-01: renders the create form with an empty name and one quantity variant', () => { it('APADD-01: renders the create form with an empty name and one quantity variant', async () => {
const view = renderAdd() const view = await renderAdd()
expect(view.getByTestId('product-name-input').props.value).toBe('') expect(view.getByTestId('product-name-input').props.value).toBe('')
expect(view.getByText('Variant 1')).toBeTruthy() expect(view.getByText('Variant 1')).toBeTruthy()
@ -69,18 +80,18 @@ describe('Add product (APADD-01..19)', () => {
}) })
it('APADD-02: a zero/missing price is rejected before the request', async () => { it('APADD-02: a zero/missing price is rejected before the request', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '0', quantity: '1kg' }) fillVariant(view, 0, { price: '0', quantity: '1kg' })
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Price must be a positive number') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Price must be a positive number'))
expect(lastMutationInput('admin.product.createProduct')).toBeUndefined() expect(lastMutationInput('admin.product.createProduct')).toBeUndefined()
}) })
it('APADD-03: duplicate variant signatures are rejected', async () => { it('APADD-03: duplicate variant signatures are rejected', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
@ -89,12 +100,12 @@ describe('Add product (APADD-01..19)', () => {
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Two variants have the same attributes') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Two variants have the same attributes'))
expect(lastMutationInput('admin.product.createProduct')).toBeUndefined() expect(lastMutationInput('admin.product.createProduct')).toBeUndefined()
}) })
it('APADD-04: every SKU is guaranteed a quantity feature', async () => { it('APADD-04: every SKU is guaranteed a quantity feature', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
@ -104,19 +115,19 @@ describe('Add product (APADD-01..19)', () => {
expect(view.getByTestId('variant-0-attr-0-name').props.editable).toBe(false) expect(view.getByTestId('variant-0-attr-0-name').props.editable).toBe(false)
await submit(view) await submit(view)
expect(lastMutationInput('admin.product.createProduct').skus[0].features).toEqual([ expect((await createdPayload()).skus[0].features).toEqual([
{ featureName: 'quantity', featureValue: '1kg' }, { featureName: 'quantity', featureValue: '1kg' },
]) ])
}) })
it('APADD-05: submits a product without images', async () => { it('APADD-05: submits a product without images', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view) await submit(view)
const payload = lastMutationInput('admin.product.createProduct') const payload = await createdPayload()
expect(payload).toEqual( expect(payload).toEqual(
expect.objectContaining({ expect.objectContaining({
name: 'Chicken', name: 'Chicken',
@ -130,7 +141,7 @@ describe('Add product (APADD-01..19)', () => {
}) })
it('APADD-06: uploads images and stores bucket-relative keys', async () => { it('APADD-06: uploads images and stores bucket-relative keys', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
@ -140,7 +151,7 @@ describe('Add product (APADD-01..19)', () => {
await submit(view) await submit(view)
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(1) expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(1)
const payload = lastMutationInput('admin.product.createProduct') const payload = await createdPayload()
expect(payload.skus[0].images).toEqual(['product-images/img-1.jpg']) expect(payload.skus[0].images).toEqual(['product-images/img-1.jpg'])
}) })
@ -153,7 +164,7 @@ describe('Add product (APADD-01..19)', () => {
], ],
}, },
}) })
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '500g' }) fillVariant(view, 0, { price: '100', quantity: '500g' })
@ -167,13 +178,13 @@ describe('Add product (APADD-01..19)', () => {
await submit(view) await submit(view)
const payload = lastMutationInput('admin.product.createProduct') const payload = await createdPayload()
expect(payload.skus[0].images).toEqual(['product-images/a.jpg']) expect(payload.skus[0].images).toEqual(['product-images/a.jpg'])
expect(payload.skus[1].images).toEqual(['product-images/b.jpg']) expect(payload.skus[1].images).toEqual(['product-images/b.jpg'])
}) })
it('APADD-08: feature names are trimmed and quantity is normalized', async () => { it('APADD-08: feature names are trimmed and quantity is normalized', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
@ -183,7 +194,7 @@ describe('Add product (APADD-01..19)', () => {
await submit(view) await submit(view)
const payload = lastMutationInput('admin.product.createProduct') const payload = await createdPayload()
expect(payload.skus[0].features).toEqual([ expect(payload.skus[0].features).toEqual([
{ featureName: 'quantity', featureValue: '1kg' }, { featureName: 'quantity', featureValue: '1kg' },
{ featureName: 'Size', featureValue: 'Large' }, { featureName: 'Size', featureValue: 'Large' },
@ -191,7 +202,7 @@ describe('Add product (APADD-01..19)', () => {
}) })
it('APADD-09: market/flash price strings become numbers', async () => { it('APADD-09: market/flash price strings become numbers', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
fireEvent.changeText(view.getByTestId('variant-0-market-price'), '250') fireEvent.changeText(view.getByTestId('variant-0-market-price'), '250')
@ -200,7 +211,7 @@ describe('Add product (APADD-01..19)', () => {
await submit(view) await submit(view)
const sku = lastMutationInput('admin.product.createProduct').skus[0] const sku = (await createdPayload()).skus[0]
expect(sku.marketPrice).toBe(250) expect(sku.marketPrice).toBe(250)
expect(sku.flashPrice).toBe(199) expect(sku.flashPrice).toBe(199)
expect(sku.isFlashAvailable).toBe(true) expect(sku.isFlashAvailable).toBe(true)
@ -208,7 +219,7 @@ describe('Add product (APADD-01..19)', () => {
it('APADD-10: create pending shows "Creating..."', async () => { it('APADD-10: create pending shows "Creating..."', async () => {
setProcedure('admin.product.createProduct', { mode: 'pending' }) setProcedure('admin.product.createProduct', { mode: 'pending' })
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
@ -219,31 +230,31 @@ describe('Add product (APADD-01..19)', () => {
}) })
it('APADD-11: success alerts and refreshes the product list', async () => { it('APADD-11: success alerts and refreshes the product list', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Product created successfully!') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Product created successfully!'))
// The list query is mounted disabled purely as a refetch handle. // The list query is mounted disabled purely as a refetch handle.
expect(procedureMutationCalls('admin.product.createProduct')).toHaveLength(1) expect(procedureMutationCalls('admin.product.createProduct')).toHaveLength(1)
}) })
it('APADD-12: API failure alerts the error message', async () => { it('APADD-12: API failure alerts the error message', async () => {
setProcedure('admin.product.createProduct', { mode: 'error', error: new Error('bad request') }) setProcedure('admin.product.createProduct', { mode: 'error', error: new Error('bad request') })
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'bad request') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'bad request'))
}) })
it('APADD-13: upload failure alerts and never creates the product', async () => { it('APADD-13: upload failure alerts and never creates the product', async () => {
setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('storage down') }) setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('storage down') })
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
@ -251,12 +262,12 @@ describe('Add product (APADD-01..19)', () => {
await flush() await flush()
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'storage down') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'storage down'))
expect(lastMutationInput('admin.product.createProduct')).toBeUndefined() expect(lastMutationInput('admin.product.createProduct')).toBeUndefined()
}) })
it('APADD-14: a create form with no store defaults to the regional store', async () => { it('APADD-14: a create form with no store defaults to the regional store', async () => {
const view = renderAdd() const view = await renderAdd()
expect(view.getAllByText('The Freshyo Meat House').length).toBeGreaterThanOrEqual(1) expect(view.getAllByText('The Freshyo Meat House').length).toBeGreaterThanOrEqual(1)
@ -264,11 +275,11 @@ describe('Add product (APADD-01..19)', () => {
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view) await submit(view)
expect(lastMutationInput('admin.product.createProduct').storeId).toBe(1) expect((await createdPayload()).storeId).toBe(1)
}) })
it('APADD-15: combo products send their combo items', async () => { it('APADD-15: combo products send their combo items', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Combo Box') fireEvent.changeText(view.getByTestId('product-name-input'), 'Combo Box')
fillVariant(view, 0, { price: '100', quantity: '1 box' }) fillVariant(view, 0, { price: '100', quantity: '1 box' })
@ -280,14 +291,14 @@ describe('Add product (APADD-01..19)', () => {
await submit(view) await submit(view)
const payload = lastMutationInput('admin.product.createProduct') const payload = await createdPayload()
expect(payload.productType).toBe('combo') expect(payload.productType).toBe('combo')
expect(payload.skus[0].comboItems).toEqual([{ skuId: 11 }]) expect(payload.skus[0].comboItems).toEqual([{ skuId: 11 }])
}) })
it('APADD-16: a global-only store list is allowed and labeled global', async () => { it('APADD-16: a global-only store list is allowed and labeled global', async () => {
setProcedure('common.getStoresSummary', { data: { stores: [STORE_GLOBAL] } }) setProcedure('common.getStoresSummary', { data: { stores: [STORE_GLOBAL] } })
const view = renderAdd() const view = await renderAdd()
expect(view.getByText('Freshyo Central (global)')).toBeTruthy() expect(view.getByText('Freshyo Central (global)')).toBeTruthy()
@ -295,11 +306,11 @@ describe('Add product (APADD-01..19)', () => {
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
await submit(view) await submit(view)
expect(lastMutationInput('admin.product.createProduct').storeId).toBe(2) expect((await createdPayload()).storeId).toBe(2)
}) })
it('APADD-17: an empty image list does not call the uploader', async () => { it('APADD-17: an empty image list does not call the uploader', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
@ -309,7 +320,7 @@ describe('Add product (APADD-01..19)', () => {
}) })
it('APADD-18: two variants with the same feature and different values are allowed', async () => { it('APADD-18: two variants with the same feature and different values are allowed', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '500g' }) fillVariant(view, 0, { price: '100', quantity: '500g' })
@ -322,14 +333,14 @@ describe('Add product (APADD-01..19)', () => {
'Check your form', 'Check your form',
'Two variants have the same attributes' 'Two variants have the same attributes'
) )
const payload = lastMutationInput('admin.product.createProduct') const payload = await createdPayload()
expect(payload.skus).toHaveLength(2) expect(payload.skus).toHaveLength(2)
expect(payload.skus[0].features[0].featureValue).toBe('500g') expect(payload.skus[0].features[0].featureValue).toBe('500g')
expect(payload.skus[1].features[0].featureValue).toBe('1kg') expect(payload.skus[1].features[0].featureValue).toBe('1kg')
}) })
it('APADD-19: duplicate signatures are detected regardless of feature order', async () => { it('APADD-19: duplicate signatures are detected regardless of feature order', async () => {
const view = renderAdd() const view = await renderAdd()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken')
fillVariant(view, 0, { price: '100', quantity: '1kg' }) fillVariant(view, 0, { price: '100', quantity: '1kg' })
@ -339,6 +350,6 @@ describe('Add product (APADD-01..19)', () => {
await submit(view) await submit(view)
// variantSignature sorts features, so equivalent attribute sets collide. // variantSignature sorts features, so equivalent attribute sets collide.
expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Two variants have the same attributes') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Check your form', 'Two variants have the same attributes'))
}) })
}) })

View file

@ -4,18 +4,19 @@
*/ */
import React from 'react' import React from 'react'
import { ActivityIndicator, Alert } from 'react-native' import { ActivityIndicator, Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
import { ImageCarousel, ImageUploader } from 'common-ui' import { ImageCarousel, ImageUploader } from 'common-ui'
import ProductDetail from '@/app/(drawer)/dashboard/products/detail/[id]' import ProductDetail from '@/app/(drawer)/dashboard/products/detail/[id]'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
procedureInvalidations, procedureInvalidations,
procedureMutationCalls, procedureMutationCalls,
setProcedure, setProcedure,
setRawFetchHandler,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { __setParams, router } from '../mocks/expo-router-mock' import { __setParams, router } from '../mocks/expo-router-mock'
import { PRODUCT_REVIEWS, P_CHICKEN, P_NO_IMAGE } from '../fixtures' import { PRODUCT_REVIEWS, P_CHICKEN, P_NO_IMAGE } from '../fixtures'
@ -56,21 +57,34 @@ const product = (over: Record<string, any> = {}) => ({
...over, ...over,
}) })
function renderDetail() { async function renderDetail() {
return renderWithProviders(<ProductDetail />, { auth: false }) const view = await renderAndFlush(<ProductDetail />, { auth: false })
await flush(2)
return view
} }
async function openReply(view: ReturnType<typeof renderDetail>) { async function openReply(view: Awaited<ReturnType<typeof renderDetail>>) {
fireEvent.press(view.getByText('Reply')) fireEvent.press(view.getByText('Reply'))
await flush() await flush()
} }
async function submitReply(view: ReturnType<typeof renderDetail>, text?: string) { async function submitReply(
view: Awaited<ReturnType<typeof renderDetail>>,
text?: string
) {
if (text !== undefined) { if (text !== undefined) {
fireEvent.changeText(view.getByPlaceholderText('Write your response here...'), text) fireEvent.changeText(view.getByPlaceholderText('Write your response here...'), text)
} }
fireEvent.press(view.getByText('Submit Response')) fireEvent.press(view.getByText('Submit Response'))
await flush(2) await flush(3)
}
/** Wait for the review-response mutation to land, then return its input. */
async function responsePayload() {
await waitFor(() =>
expect(lastMutationInput('admin.product.respondToReview')).toBeDefined()
)
return lastMutationInput('admin.product.respondToReview')
} }
describe('Product detail (APDET-01..22)', () => { describe('Product detail (APDET-01..22)', () => {
@ -80,11 +94,11 @@ describe('Product detail (APDET-01..22)', () => {
resetAllMocks() resetAllMocks()
__setParams({ id: '2' }) __setParams({ id: '2' })
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
;(global as any).fetch = jest.fn(async (_url: string, init?: any) => { setRawFetchHandler(async (_url, init) => {
if (init?.method === 'PUT') { if (init?.method === 'PUT') {
return { ok: true, status: 200, text: async () => '' } return { ok: true, status: 200, text: async () => '' } as any
} }
return { ok: true, status: 200, blob: async () => ({ size: 1 }) } return { ok: true, status: 200, blob: async () => ({ size: 1 }) } as any
}) })
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({ ;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({
canceled: false, canceled: false,
@ -94,51 +108,51 @@ describe('Product detail (APDET-01..22)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('APDET-01: shows a spinner and loading copy', () => { it('APDET-01: shows a spinner and loading copy', async () => {
setProcedure('admin.product.getProductById', { mode: 'pending' }) setProcedure('admin.product.getProductById', { mode: 'pending' })
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('Loading...')).toBeTruthy() expect(view.getByText('Loading...')).toBeTruthy()
expect(view.UNSAFE_getByType(ActivityIndicator)).toBeTruthy() expect(view.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
}) })
it('APDET-02: shows Product Not Found with a Go Back action', () => { it('APDET-02: shows Product Not Found with a Go Back action', async () => {
setProcedure('admin.product.getProductById', { mode: 'error', error: new Error('gone') }) setProcedure('admin.product.getProductById', { mode: 'error', error: new Error('gone') })
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('Product Not Found')).toBeTruthy() expect(await view.findByText('Product Not Found')).toBeTruthy()
fireEvent.press(view.getByText('Go Back')) fireEvent.press(view.getByText('Go Back'))
expect(router.back).toHaveBeenCalled() expect(router.back).toHaveBeenCalled()
}) })
it('APDET-03: renders the hero carousel, name and variant count', () => { it('APDET-03: renders the hero carousel, name and variant count', async () => {
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('Chicken Breast')).toBeTruthy() expect(view.getByText('Chicken Breast')).toBeTruthy()
expect(view.getByText('2 Variants')).toBeTruthy() expect(view.getByText('2 Variants')).toBeTruthy()
expect(view.UNSAFE_getByType(ImageCarousel)).toBeTruthy() expect(view.UNSAFE_getByType(ImageCarousel)).toBeTruthy()
}) })
it('APDET-04: renders a gray hero when the product has no images', () => { it('APDET-04: renders a gray hero when the product has no images', async () => {
setProcedure('admin.product.getProductById', { setProcedure('admin.product.getProductById', {
data: { product: { ...P_NO_IMAGE, deals: [], tags: [] } }, data: { product: { ...P_NO_IMAGE, deals: [], tags: [] } },
}) })
const view = renderDetail() const view = await renderDetail()
expect(view.getByTestId('product-hero-placeholder')).toBeTruthy() expect(view.getByTestId('product-hero-placeholder')).toBeTruthy()
expect(view.UNSAFE_queryByType(ImageCarousel)).toBeNull() expect(view.UNSAFE_queryByType(ImageCarousel)).toBeNull()
}) })
it('APDET-05: calculates the average rating to one decimal', () => { it('APDET-05: calculates the average rating to one decimal', async () => {
const view = renderDetail() const view = await renderDetail()
// Ratings 5 and 3 from the default review fixture. // Ratings 5 and 3 from the default review fixture.
expect(view.getByText('4.0')).toBeTruthy() expect(view.getByText('4.0')).toBeTruthy()
}) })
it('APDET-06: with no reviews the rating is "-" and the count is 0', () => { it('APDET-06: with no reviews the rating is "-" and the count is 0', async () => {
setProcedure('admin.product.getProductReviews', { data: { reviews: [], hasMore: false } }) setProcedure('admin.product.getProductReviews', { data: { reviews: [], hasMore: false } })
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('-')).toBeTruthy() expect(view.getByText('-')).toBeTruthy()
expect(view.getByText('0')).toBeTruthy() expect(view.getByText('0')).toBeTruthy()
@ -146,17 +160,17 @@ describe('Product detail (APDET-01..22)', () => {
expect(view.getByText('No reviews yet')).toBeTruthy() expect(view.getByText('No reviews yet')).toBeTruthy()
}) })
it('APDET-07: renders short and long descriptions with a fallback', () => { it('APDET-07: renders short and long descriptions with a fallback', async () => {
setProcedure('admin.product.getProductById', { setProcedure('admin.product.getProductById', {
data: { product: product({ longDescription: '' }) }, data: { product: product({ longDescription: '' }) },
}) })
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('Tender boneless breast')).toBeTruthy() expect(view.getByText('Tender boneless breast')).toBeTruthy()
expect(view.getByText('No detailed description available for this product.')).toBeTruthy() expect(view.getByText('No detailed description available for this product.')).toBeTruthy()
}) })
it('APDET-08: renders variant features, prices, flash price and stock', () => { it('APDET-08: renders variant features, prices, flash price and stock', async () => {
setProcedure('admin.product.getProductById', { setProcedure('admin.product.getProductById', {
data: { data: {
product: product({ product: product({
@ -171,7 +185,7 @@ describe('Product detail (APDET-01..22)', () => {
}), }),
}, },
}) })
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('quantity')).toBeTruthy() expect(view.getByText('quantity')).toBeTruthy()
expect(view.getByText('500g')).toBeTruthy() expect(view.getByText('500g')).toBeTruthy()
@ -181,7 +195,7 @@ describe('Product detail (APDET-01..22)', () => {
expect(view.getByText('In Stock')).toBeTruthy() expect(view.getByText('In Stock')).toBeTruthy()
}) })
it('APDET-09: renders special deals with quantity, price and validity', () => { it('APDET-09: renders special deals with quantity, price and validity', async () => {
setProcedure('admin.product.getProductById', { setProcedure('admin.product.getProductById', {
data: { data: {
product: product({ product: product({
@ -189,7 +203,7 @@ describe('Product detail (APDET-01..22)', () => {
}), }),
}, },
}) })
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('Special Deals')).toBeTruthy() expect(view.getByText('Special Deals')).toBeTruthy()
expect(view.getByText('Buy 2')).toBeTruthy() expect(view.getByText('Buy 2')).toBeTruthy()
@ -197,7 +211,7 @@ describe('Product detail (APDET-01..22)', () => {
expect(view.getByText(/Valid until/)).toBeTruthy() expect(view.getByText(/Valid until/)).toBeTruthy()
}) })
it('APDET-10: renders the review list with user, body and images', () => { it('APDET-10: renders the review list with user, body and images', async () => {
setProcedure('admin.product.getProductReviews', { setProcedure('admin.product.getProductReviews', {
data: { data: {
reviews: [ reviews: [
@ -209,7 +223,7 @@ describe('Product detail (APDET-01..22)', () => {
hasMore: false, hasMore: false,
}, },
}) })
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('A')).toBeTruthy() expect(view.getByText('A')).toBeTruthy()
expect(view.getByText('Great')).toBeTruthy() expect(view.getByText('Great')).toBeTruthy()
@ -217,21 +231,21 @@ describe('Product detail (APDET-01..22)', () => {
expect(view.getAllByLabelText('https://assets.test/review.jpg')).toHaveLength(1) expect(view.getAllByLabelText('https://assets.test/review.jpg')).toHaveLength(1)
}) })
it('APDET-11: renders an existing admin response block', () => { it('APDET-11: renders an existing admin response block', async () => {
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('Admin Response')).toBeTruthy() expect(view.getByText('Admin Response')).toBeTruthy()
expect(view.getByText('Thanks')).toBeTruthy() expect(view.getByText('Thanks')).toBeTruthy()
}) })
it('APDET-12: a review without a response exposes Reply', () => { it('APDET-12: a review without a response exposes Reply', async () => {
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('Reply')).toBeTruthy() expect(view.getByText('Reply')).toBeTruthy()
}) })
it('APDET-13: Reply opens a dialog that quotes the review', async () => { it('APDET-13: Reply opens a dialog that quotes the review', async () => {
const view = renderDetail() const view = await renderDetail()
await openReply(view) await openReply(view)
@ -241,36 +255,38 @@ describe('Product detail (APDET-01..22)', () => {
}) })
it('APDET-14: submitting a response uploads, mutates, invalidates and closes', async () => { it('APDET-14: submitting a response uploads, mutates, invalidates and closes', async () => {
const view = renderDetail() const view = await renderDetail()
await openReply(view) await openReply(view)
await submitReply(view, 'Thanks for the feedback') await submitReply(view, 'Thanks for the feedback')
expect(lastMutationInput('admin.product.respondToReview')).toEqual({ expect(await responsePayload()).toEqual({
reviewId: 1, reviewId: 1,
adminResponse: 'Thanks for the feedback', adminResponse: 'Thanks for the feedback',
adminResponseImages: [], adminResponseImages: [],
uploadUrls: [], uploadUrls: [],
}) })
await waitFor(() =>
expect(procedureInvalidations('admin.product.getProductReviews')).toHaveLength(1) expect(procedureInvalidations('admin.product.getProductReviews')).toHaveLength(1)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Response submitted') )
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Response submitted'))
expect(view.queryByText('Reply to Review')).toBeNull() expect(view.queryByText('Reply to Review')).toBeNull()
}) })
it('APDET-15: an empty response is submitted as-is', async () => { it('APDET-15: an empty response is submitted as-is', async () => {
const view = renderDetail() const view = await renderDetail()
await openReply(view) await openReply(view)
await submitReply(view) await submitReply(view)
expect(lastMutationInput('admin.product.respondToReview')).toEqual( expect(await responsePayload()).toEqual(
expect.objectContaining({ reviewId: 1, adminResponse: '' }) expect.objectContaining({ reviewId: 1, adminResponse: '' })
) )
}) })
it('APDET-16: a pending response shows a spinner', async () => { it('APDET-16: a pending response shows a spinner', async () => {
setProcedure('admin.product.respondToReview', { mode: 'pending' }) setProcedure('admin.product.respondToReview', { mode: 'pending' })
const view = renderDetail() const view = await renderDetail()
await openReply(view) await openReply(view)
fireEvent.press(view.getByText('Submit Response')) fireEvent.press(view.getByText('Submit Response'))
@ -285,25 +301,25 @@ describe('Product detail (APDET-01..22)', () => {
mode: 'error', mode: 'error',
error: new Error('respond failed'), error: new Error('respond failed'),
}) })
const view = renderDetail() const view = await renderDetail()
await openReply(view) await openReply(view)
await submitReply(view, 'hello') await submitReply(view, 'hello')
expect(alertSpy).toHaveBeenCalledWith('Error', 'respond failed') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'respond failed'))
expect(view.getByText('Reply to Review')).toBeTruthy() expect(view.getByText('Reply to Review')).toBeTruthy()
}) })
it('APDET-18: Edit opens the edit route', () => { it('APDET-18: Edit opens the edit route', async () => {
const view = renderDetail() const view = await renderDetail()
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit?id=2') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit?id=2')
}) })
it('APDET-19: the back button calls router.back', () => { it('APDET-19: the back button calls router.back', async () => {
const view = renderDetail() const view = await renderDetail()
fireEvent.press(view.getByTestId('product-detail-back')) fireEvent.press(view.getByTestId('product-detail-back'))
@ -311,7 +327,7 @@ describe('Product detail (APDET-01..22)', () => {
}) })
it('APDET-20: a focus refetches through the marked data fetcher', async () => { it('APDET-20: a focus refetches through the marked data fetcher', async () => {
const view = renderDetail() const view = await renderDetail()
expect(navMock.__focusCallbacks.length).toBeGreaterThan(0) expect(navMock.__focusCallbacks.length).toBeGreaterThan(0)
await act(async () => { await act(async () => {
@ -323,7 +339,7 @@ describe('Product detail (APDET-01..22)', () => {
it('APDET-21: a review image upload failure alerts and skips the response', async () => { it('APDET-21: a review image upload failure alerts and skips the response', async () => {
setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('upload failed') }) setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('upload failed') })
const view = renderDetail() const view = await renderDetail()
await openReply(view) await openReply(view)
@ -335,11 +351,11 @@ describe('Product detail (APDET-01..22)', () => {
await submitReply(view, 'with image') await submitReply(view, 'with image')
expect(alertSpy).toHaveBeenCalledWith('Error', 'upload failed') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'upload failed'))
expect(procedureMutationCalls('admin.product.respondToReview')).toHaveLength(0) expect(procedureMutationCalls('admin.product.respondToReview')).toHaveLength(0)
}) })
it('APDET-22: many variants and reviews render without crashing', () => { it('APDET-22: many variants and reviews render without crashing', async () => {
const manySkus = Array.from({ length: 25 }, (_, index) => ({ const manySkus = Array.from({ length: 25 }, (_, index) => ({
...P_CHICKEN.skus[0], ...P_CHICKEN.skus[0],
id: 500 + index, id: 500 + index,
@ -356,7 +372,7 @@ describe('Product detail (APDET-01..22)', () => {
setProcedure('admin.product.getProductById', { data: { product: product({ skus: manySkus }) } }) setProcedure('admin.product.getProductById', { data: { product: product({ skus: manySkus }) } })
setProcedure('admin.product.getProductReviews', { data: { reviews: manyReviews, hasMore: false } }) setProcedure('admin.product.getProductReviews', { data: { reviews: manyReviews, hasMore: false } })
const view = renderDetail() const view = await renderDetail()
expect(view.getByText('25 Variants')).toBeTruthy() expect(view.getByText('25 Variants')).toBeTruthy()
expect(view.getByText('30 Total')).toBeTruthy() expect(view.getByText('30 Total')).toBeTruthy()

View file

@ -4,17 +4,18 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, DeviceEventEmitter } from 'react-native' import { Alert, DeviceEventEmitter } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
import EditProduct from '@/app/(drawer)/dashboard/products/edit' import EditProduct from '@/app/(drawer)/dashboard/products/edit'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
procedureMutationCalls, procedureMutationCalls,
procedureQueryCalls, procedureQueryCalls,
setProcedure, setProcedure,
setRawFetchHandler,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { __setParams } from '../mocks/expo-router-mock' import { __setParams } from '../mocks/expo-router-mock'
import { P_CHICKEN, P_GLOBAL } from '../fixtures' import { P_CHICKEN, P_GLOBAL } from '../fixtures'
@ -34,26 +35,36 @@ const globalProduct = (over: Record<string, any> = {}) => ({
...over, ...over,
}) })
function renderEdit() { async function renderEdit() {
return renderWithProviders(<EditProduct />, { auth: false }) const view = await renderAndFlush(<EditProduct />, { auth: false })
await flush(2)
return view
} }
async function submit(view: ReturnType<typeof renderEdit>) { async function submit(view: Awaited<ReturnType<typeof renderEdit>>) {
fireEvent.press(view.getByTestId('create-product-button')) fireEvent.press(view.getByTestId('create-product-button'))
await flush(2) await flush(3)
} }
async function submitGlobal(view: ReturnType<typeof renderEdit>) { async function submitGlobal(view: Awaited<ReturnType<typeof renderEdit>>) {
fireEvent.press(view.getByTestId('global-save-button')) fireEvent.press(view.getByTestId('global-save-button'))
await flush(2) await flush(3)
}
/** Wait for the update mutation to land, then return its input. */
async function updatedPayload() {
await waitFor(() =>
expect(lastMutationInput('admin.product.updateProduct')).toBeDefined()
)
return lastMutationInput('admin.product.updateProduct')
} }
function mockSuccessfulUploads() { function mockSuccessfulUploads() {
;(global as any).fetch = jest.fn(async (_url: string, init?: any) => { setRawFetchHandler(async (_url, init) => {
if (init?.method === 'PUT') { if (init?.method === 'PUT') {
return { ok: true, status: 200, text: async () => '' } return { ok: true, status: 200, text: async () => '' } as any
} }
return { ok: true, status: 200, blob: async () => ({ size: 1 }) } return { ok: true, status: 200, blob: async () => ({ size: 1 }) } as any
}) })
} }
@ -73,45 +84,45 @@ describe('Edit product (APEDIT-01..20)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('APEDIT-01: a missing/invalid id disables the query and shows not found', () => { it('APEDIT-01: a missing/invalid id disables the query and shows not found', async () => {
__setParams({}) __setParams({})
const view = renderEdit() const view = await renderEdit()
expect(view.getByText('Product not found')).toBeTruthy() expect(view.getByText('Product not found')).toBeTruthy()
expect(procedureQueryCalls('admin.product.getProductById')).toHaveLength(0) expect(procedureQueryCalls('admin.product.getProductById')).toHaveLength(0)
view.unmount() view.unmount()
__setParams({ id: 'abc' }) __setParams({ id: 'abc' })
const second = renderEdit() const second = await renderEdit()
expect(second.getByText('Product not found')).toBeTruthy() expect(second.getByText('Product not found')).toBeTruthy()
expect(procedureQueryCalls('admin.product.getProductById')).toHaveLength(0) expect(procedureQueryCalls('admin.product.getProductById')).toHaveLength(0)
}) })
it('APEDIT-02: shows the loading copy while the product is fetching', () => { it('APEDIT-02: shows the loading copy while the product is fetching', async () => {
setProcedure('admin.product.getProductById', { mode: 'pending' }) setProcedure('admin.product.getProductById', { mode: 'pending' })
const view = renderEdit() const view = await renderEdit()
expect(view.getByText('Loading product...')).toBeTruthy() expect(view.getByText('Loading product...')).toBeTruthy()
}) })
it('APEDIT-03: a regular product prefills the ProductForm', () => { it('APEDIT-03: a regular product prefills the ProductForm', async () => {
const view = renderEdit() const view = await renderEdit()
expect(view.getByTestId('product-name-input').props.value).toBe('Chicken Breast') expect(view.getByTestId('product-name-input').props.value).toBe('Chicken Breast')
expect(view.getByTestId('variant-0-price').props.value).toBe('215') expect(view.getByTestId('variant-0-price').props.value).toBe('215')
expect(view.getByText('Variant 1')).toBeTruthy() expect(view.getByText('Variant 1')).toBeTruthy()
}) })
it('APEDIT-04: a global product renders GlobalProductForm with read-only structure', () => { it('APEDIT-04: a global product renders GlobalProductForm with read-only structure', async () => {
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } }) setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
const view = renderEdit() const view = await renderEdit()
expect(view.getByText('Global product')).toBeTruthy() expect(view.getByText('Global product')).toBeTruthy()
expect(view.queryByTestId('product-name-input')).toBeNull() expect(view.queryByTestId('product-name-input')).toBeNull()
expect(view.getAllByText('Global Paneer').length).toBeGreaterThanOrEqual(1) expect(view.getAllByText('Global Paneer').length).toBeGreaterThanOrEqual(1)
}) })
it('APEDIT-05: the global suspend toggle starts from the SKU state', () => { it('APEDIT-05: the global suspend toggle starts from the SKU state', async () => {
setProcedure('admin.product.getProductById', { setProcedure('admin.product.getProductById', {
data: { data: {
product: globalProduct({ product: globalProduct({
@ -119,18 +130,18 @@ describe('Edit product (APEDIT-01..20)', () => {
}), }),
}, },
}) })
const view = renderEdit() const view = await renderEdit()
expect(view.getByTestId('global-sku-91-suspend').props.accessibilityState.checked).toBe(true) expect(view.getByTestId('global-sku-91-suspend').props.accessibilityState.checked).toBe(true)
}) })
it('APEDIT-06: saving a regular product keeps existing images', async () => { it('APEDIT-06: saving a regular product keeps existing images', async () => {
const view = renderEdit() const view = await renderEdit()
fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken Updated') fireEvent.changeText(view.getByTestId('product-name-input'), 'Chicken Updated')
await submit(view) await submit(view)
const payload = lastMutationInput('admin.product.updateProduct') const payload = await updatedPayload()
expect(payload).toEqual( expect(payload).toEqual(
expect.objectContaining({ expect.objectContaining({
id: 2, id: 2,
@ -147,52 +158,52 @@ describe('Edit product (APEDIT-01..20)', () => {
}) })
it('APEDIT-07: removing an existing image records its key as deleted', async () => { it('APEDIT-07: removing an existing image records its key as deleted', async () => {
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('variant-0-image-add-remove')) fireEvent.press(view.getByTestId('variant-0-image-add-remove'))
await submit(view) await submit(view)
const payload = lastMutationInput('admin.product.updateProduct') const payload = await updatedPayload()
expect(payload.deletedImageKeys).toEqual(['product-images/chicken.jpg']) expect(payload.deletedImageKeys).toEqual(['product-images/chicken.jpg'])
expect(payload.skus[0].images).toEqual([]) expect(payload.skus[0].images).toEqual([])
}) })
it('APEDIT-08: new images are uploaded and appended as keys', async () => { it('APEDIT-08: new images are uploaded and appended as keys', async () => {
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('variant-0-image-add')) fireEvent.press(view.getByTestId('variant-0-image-add'))
await flush() await flush()
await submit(view) await submit(view)
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(1) expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(1)
const payload = lastMutationInput('admin.product.updateProduct') const payload = await updatedPayload()
expect(payload.newImageUrls).toEqual(['https://upload.test/meatfarmer/product-images/img-1.jpg']) expect(payload.newImageUrls).toEqual(['https://upload.test/meatfarmer/product-images/img-1.jpg'])
expect(payload.skus[0].images).toEqual(['chicken.jpg', 'product-images/img-1.jpg']) expect(payload.skus[0].images).toEqual(['chicken.jpg', 'product-images/img-1.jpg'])
}) })
it('APEDIT-09: submitting without changes still sends the product', async () => { it('APEDIT-09: submitting without changes still sends the product', async () => {
const view = renderEdit() const view = await renderEdit()
await submit(view) await submit(view)
const payload = lastMutationInput('admin.product.updateProduct') const payload = await updatedPayload()
expect(payload.id).toBe(2) expect(payload.id).toBe(2)
expect(payload.name).toBe('Chicken Breast') expect(payload.name).toBe('Chicken Breast')
}) })
it('APEDIT-10: a failed update alerts and stays on the page', async () => { it('APEDIT-10: a failed update alerts and stays on the page', async () => {
setProcedure('admin.product.updateProduct', { mode: 'error', error: new Error('nope') }) setProcedure('admin.product.updateProduct', { mode: 'error', error: new Error('nope') })
const view = renderEdit() const view = await renderEdit()
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'nope') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope'))
expect(view.getByTestId('product-name-input').props.value).toBe('Chicken Breast') expect(view.getByTestId('product-name-input').props.value).toBe('Chicken Breast')
}) })
it('APEDIT-11: update pending shows "Saving..."', async () => { it('APEDIT-11: update pending shows "Saving..."', async () => {
setProcedure('admin.product.updateProduct', { mode: 'pending' }) setProcedure('admin.product.updateProduct', { mode: 'pending' })
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('create-product-button')) fireEvent.press(view.getByTestId('create-product-button'))
await flush(2) await flush(2)
@ -201,26 +212,26 @@ describe('Edit product (APEDIT-01..20)', () => {
}) })
it('APEDIT-12: success alerts, refetches and clears uploaded images', async () => { it('APEDIT-12: success alerts, refetches and clears uploaded images', async () => {
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('variant-0-image-add')) fireEvent.press(view.getByTestId('variant-0-image-add'))
await flush() await flush()
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Product updated successfully!') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Product updated successfully!'))
expect(view.queryByTestId('variant-0-image-add-remove')).toBeNull() expect(view.queryByTestId('variant-0-image-add-remove')).toBeNull()
}) })
it('APEDIT-13: saving a global product sends market fields', async () => { it('APEDIT-13: saving a global product sends market fields', async () => {
__setParams({ id: '9' }) __setParams({ id: '9' })
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } }) setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
const view = renderEdit() const view = await renderEdit()
fireEvent.changeText(view.getByTestId('global-sku-91-price'), '95') fireEvent.changeText(view.getByTestId('global-sku-91-price'), '95')
await submitGlobal(view) await submitGlobal(view)
const payload = lastMutationInput('admin.product.updateProduct') const payload = await updatedPayload()
expect(payload).toEqual( expect(payload).toEqual(
expect.objectContaining({ expect.objectContaining({
id: 9, id: 9,
@ -233,26 +244,26 @@ describe('Edit product (APEDIT-01..20)', () => {
}) })
) )
expect(payload.skus[0].price).toBe(95) expect(payload.skus[0].price).toBe(95)
expect(alertSpy).toHaveBeenCalledWith('Success', 'Market data updated for your region') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Market data updated for your region'))
}) })
it('APEDIT-14: a global product with storeId 0 sends storeId 0', async () => { it('APEDIT-14: a global product with storeId 0 sends storeId 0', async () => {
setProcedure('admin.product.getProductById', { data: { product: globalProduct({ storeId: 0 }) } }) setProcedure('admin.product.getProductById', { data: { product: globalProduct({ storeId: 0 }) } })
const view = renderEdit() const view = await renderEdit()
await submitGlobal(view) await submitGlobal(view)
expect(lastMutationInput('admin.product.updateProduct').storeId).toBe(0) expect((await updatedPayload()).storeId).toBe(0)
}) })
it('APEDIT-15: an empty global price is sent as 0', async () => { it('APEDIT-15: an empty global price is sent as 0', async () => {
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } }) setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
const view = renderEdit() const view = await renderEdit()
fireEvent.changeText(view.getByTestId('global-sku-91-price'), '') fireEvent.changeText(view.getByTestId('global-sku-91-price'), '')
await submitGlobal(view) await submitGlobal(view)
expect(lastMutationInput('admin.product.updateProduct').skus[0].price).toBe(0) expect((await updatedPayload()).skus[0].price).toBe(0)
}) })
it('APEDIT-16: turning flash off sends a null flash price', async () => { it('APEDIT-16: turning flash off sends a null flash price', async () => {
@ -263,39 +274,39 @@ describe('Edit product (APEDIT-01..20)', () => {
}), }),
}, },
}) })
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('global-sku-91-flash')) fireEvent.press(view.getByTestId('global-sku-91-flash'))
await submitGlobal(view) await submitGlobal(view)
const sku = lastMutationInput('admin.product.updateProduct').skus[0] const sku = (await updatedPayload()).skus[0]
expect(sku.isFlashAvailable).toBe(false) expect(sku.isFlashAvailable).toBe(false)
expect(sku.flashPrice).toBeNull() expect(sku.flashPrice).toBeNull()
}) })
it('APEDIT-17: suspending a global SKU sends the flag', async () => { it('APEDIT-17: suspending a global SKU sends the flag', async () => {
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } }) setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('global-sku-91-suspend')) fireEvent.press(view.getByTestId('global-sku-91-suspend'))
await submitGlobal(view) await submitGlobal(view)
expect(lastMutationInput('admin.product.updateProduct').skus[0].isSuspended).toBe(true) expect((await updatedPayload()).skus[0].isSuspended).toBe(true)
}) })
it('APEDIT-18: a failed global save alerts', async () => { it('APEDIT-18: a failed global save alerts', async () => {
setProcedure('admin.product.getProductById', { data: { product: globalProduct() } }) setProcedure('admin.product.getProductById', { data: { product: globalProduct() } })
setProcedure('admin.product.updateProduct', { mode: 'error', error: new Error('no market') }) setProcedure('admin.product.updateProduct', { mode: 'error', error: new Error('no market') })
const view = renderEdit() const view = await renderEdit()
await submitGlobal(view) await submitGlobal(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'no market') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'no market'))
}) })
it('APEDIT-19: the manual refresh event refetches the product', async () => { it('APEDIT-19: the manual refresh event refetches the product', async () => {
const addListener = jest.spyOn(DeviceEventEmitter, 'addListener') const addListener = jest.spyOn(DeviceEventEmitter, 'addListener')
const view = renderEdit() const view = await renderEdit()
const refreshListener = addListener.mock.calls.find(([event]) => event === REFRESH_EVENT)?.[1] as const refreshListener = addListener.mock.calls.find(([event]) => event === REFRESH_EVENT)?.[1] as
| ((...args: any[]) => any) | ((...args: any[]) => any)
@ -327,11 +338,11 @@ describe('Edit product (APEDIT-01..20)', () => {
}), }),
}, },
}) })
const view = renderEdit() const view = await renderEdit()
await submit(view) await submit(view)
const payload = lastMutationInput('admin.product.updateProduct') const payload = await updatedPayload()
expect(payload.skus[0].images).toEqual(['product-images/1.jpg']) expect(payload.skus[0].images).toEqual(['product-images/1.jpg'])
}) })
}) })

View file

@ -4,11 +4,11 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import { BottomDropdown } from 'common-ui' import { BottomDropdown } from 'common-ui'
import CreateProductGroup from '@/app/(drawer)/dashboard/product-groupings/create' import CreateProductGroup from '@/app/(drawer)/dashboard/product-groupings/create'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -17,10 +17,10 @@ import {
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
type View = ReturnType<typeof renderCreate>['view'] type View = Awaited<ReturnType<typeof renderCreate>>['view']
function renderCreate() { async function renderCreate() {
const view = renderWithProviders(<CreateProductGroup />, { auth: false }) const view = await renderAndFlush(<CreateProductGroup />, { auth: false })
return { view } return { view }
} }
@ -43,15 +43,15 @@ describe('Product group create (AGRPC-01..07)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('AGRPC-01: renders Create Product Group', () => { it('AGRPC-01: renders Create Product Group', async () => {
const { view } = renderCreate() const { view } = await renderCreate()
expect(view.getByText('Create Product Group')).toBeTruthy() expect(view.getByText('Create Product Group')).toBeTruthy()
expect(nameInput(view)).toBeTruthy() expect(nameInput(view)).toBeTruthy()
}) })
it('AGRPC-02: an empty name is a validation error', async () => { it('AGRPC-02: an empty name is a validation error', async () => {
const { view } = renderCreate() const { view } = await renderCreate()
await submit(view) await submit(view)
@ -60,7 +60,7 @@ describe('Product group create (AGRPC-01..07)', () => {
}) })
it('AGRPC-03: creates the group and goes back', async () => { it('AGRPC-03: creates the group and goes back', async () => {
const { view } = renderCreate() const { view } = await renderCreate()
fireEvent.changeText(nameInput(view), 'Breakfast') fireEvent.changeText(nameInput(view), 'Breakfast')
fireEvent.changeText(view.getByPlaceholderText('Enter description (optional)'), 'Morning') fireEvent.changeText(view.getByPlaceholderText('Enter description (optional)'), 'Morning')
@ -75,7 +75,7 @@ describe('Product group create (AGRPC-01..07)', () => {
}) })
it('AGRPC-04: an empty description is allowed', async () => { it('AGRPC-04: an empty description is allowed', async () => {
const { view } = renderCreate() const { view } = await renderCreate()
fireEvent.changeText(nameInput(view), 'Only Name') fireEvent.changeText(nameInput(view), 'Only Name')
await submit(view) await submit(view)
@ -87,7 +87,7 @@ describe('Product group create (AGRPC-01..07)', () => {
}) })
it('AGRPC-05: product selection is sent as product_ids', async () => { it('AGRPC-05: product selection is sent as product_ids', async () => {
const { view } = renderCreate() const { view } = await renderCreate()
fireEvent.changeText(nameInput(view), 'Combo') fireEvent.changeText(nameInput(view), 'Combo')
const dropdown = view.UNSAFE_getAllByType(BottomDropdown)[0] const dropdown = view.UNSAFE_getAllByType(BottomDropdown)[0]
@ -104,17 +104,17 @@ describe('Product group create (AGRPC-01..07)', () => {
mode: 'error', mode: 'error',
error: new Error('Bad group'), error: new Error('Bad group'),
}) })
const { view } = renderCreate() const { view } = await renderCreate()
fireEvent.changeText(nameInput(view), 'Breakfast') fireEvent.changeText(nameInput(view), 'Breakfast')
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Bad group') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'Bad group'))
}) })
it('AGRPC-07: a pending create shows Saving...', async () => { it('AGRPC-07: a pending create shows Saving...', async () => {
setProcedure('admin.product.createGroup', { mode: 'pending' }) setProcedure('admin.product.createGroup', { mode: 'pending' })
const { view } = renderCreate() const { view } = await renderCreate()
fireEvent.changeText(nameInput(view), 'Breakfast') fireEvent.changeText(nameInput(view), 'Breakfast')
await submit(view) await submit(view)

View file

@ -6,7 +6,7 @@ import React from 'react'
import { fireEvent } from '@testing-library/react-native' import { fireEvent } from '@testing-library/react-native'
import EditProductGroup from '@/app/(drawer)/dashboard/product-groupings/edit/[id]' import EditProductGroup from '@/app/(drawer)/dashboard/product-groupings/edit/[id]'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -16,12 +16,13 @@ import {
import { router, __setParams } from '../mocks/expo-router-mock' import { router, __setParams } from '../mocks/expo-router-mock'
import { GROUP_1 } from '../fixtures' import { GROUP_1 } from '../fixtures'
type View = ReturnType<typeof renderEdit>['view'] type View = Awaited<ReturnType<typeof renderEdit>>['view']
function renderEdit(id = '1', groups = [GROUP_1]) { async function renderEdit(id = '1', groups = [GROUP_1]) {
__setParams({ id }) __setParams({ id })
setProcedure('admin.product.getGroups', { data: { groups } }) setProcedure('admin.product.getGroups', { data: { groups } })
const view = renderWithProviders(<EditProductGroup />, { auth: false }) const view = await renderAndFlush(<EditProductGroup />, { auth: false })
await flush(2)
return { view } return { view }
} }
@ -37,14 +38,14 @@ async function submit(view: View) {
describe('Product group edit (AGRPE-01..08)', () => { describe('Product group edit (AGRPE-01..08)', () => {
beforeEach(() => resetAllMocks()) beforeEach(() => resetAllMocks())
it('AGRPE-01: loads the group into the edit form', () => { it('AGRPE-01: loads the group into the edit form', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
expect(view.getByText('Edit Product Group')).toBeTruthy() expect(view.getByText('Edit Product Group')).toBeTruthy()
expect(nameInput(view).props.value).toBe('Breakfast') expect(nameInput(view).props.value).toBe('Breakfast')
}) })
it('AGRPE-02: shows loading while the groups query is pending', () => { it('AGRPE-02: shows loading while the groups query is pending', async () => {
setProcedure('admin.product.getGroups', { mode: 'pending' }) setProcedure('admin.product.getGroups', { mode: 'pending' })
__setParams({ id: '1' }) __setParams({ id: '1' })
const view = renderWithProviders(<EditProductGroup />, { auth: false }) const view = renderWithProviders(<EditProductGroup />, { auth: false })
@ -52,8 +53,8 @@ describe('Product group edit (AGRPE-01..08)', () => {
expect(view.getByText('Loading group...')).toBeTruthy() expect(view.getByText('Loading group...')).toBeTruthy()
}) })
it('AGRPE-03: prefills name, description and products', () => { it('AGRPE-03: prefills name, description and products', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
expect(nameInput(view).props.value).toBe('Breakfast') expect(nameInput(view).props.value).toBe('Breakfast')
expect(view.getByPlaceholderText('Enter description (optional)').props.value).toBe( expect(view.getByPlaceholderText('Enter description (optional)').props.value).toBe(
@ -63,7 +64,7 @@ describe('Product group edit (AGRPE-01..08)', () => {
}) })
it('AGRPE-04: saving calls updateGroup with the edited values', async () => { it('AGRPE-04: saving calls updateGroup with the edited values', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
fireEvent.changeText(nameInput(view), 'Breakfast Plus') fireEvent.changeText(nameInput(view), 'Breakfast Plus')
await submit(view) await submit(view)
@ -76,14 +77,14 @@ describe('Product group edit (AGRPE-01..08)', () => {
}) })
}) })
it('AGRPE-05: an unknown group id shows Group not found', () => { it('AGRPE-05: an unknown group id shows Group not found', async () => {
const { view } = renderEdit('999') const { view } = await renderEdit('999')
expect(view.getByText('Group not found')).toBeTruthy() expect(view.getByText('Group not found')).toBeTruthy()
}) })
it('AGRPE-06: product ids are the group SKU ids end-to-end', async () => { it('AGRPE-06: product ids are the group SKU ids end-to-end', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
expect(view.getByText('Chicken Breast - 500g, Cucumber - 500g')).toBeTruthy() expect(view.getByText('Chicken Breast - 500g, Cucumber - 500g')).toBeTruthy()
await submit(view) await submit(view)
@ -92,7 +93,7 @@ describe('Product group edit (AGRPE-01..08)', () => {
}) })
it('AGRPE-07: success invalidates the groups list and goes back', async () => { it('AGRPE-07: success invalidates the groups list and goes back', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
fireEvent.changeText(nameInput(view), 'Updated') fireEvent.changeText(nameInput(view), 'Updated')
await submit(view) await submit(view)
@ -101,8 +102,8 @@ describe('Product group edit (AGRPE-01..08)', () => {
expect(router.back).toHaveBeenCalled() expect(router.back).toHaveBeenCalled()
}) })
it('AGRPE-08: Cancel goes back', () => { it('AGRPE-08: Cancel goes back', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
fireEvent.press(view.getByText('Cancel')) fireEvent.press(view.getByText('Cancel'))

View file

@ -9,7 +9,7 @@ import { MyTouchableOpacity } from 'common-ui'
import { MaterialIcons } from '@expo/vector-icons' import { MaterialIcons } from '@expo/vector-icons'
import ProductGroupings from '@/app/(drawer)/dashboard/product-groupings/index' import ProductGroupings from '@/app/(drawer)/dashboard/product-groupings/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -19,11 +19,11 @@ import {
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { GROUP_1 } from '../fixtures' import { GROUP_1 } from '../fixtures'
type View = ReturnType<typeof renderGroups>['view'] type View = Awaited<ReturnType<typeof renderGroups>>['view']
function renderGroups(groups: any[] = [GROUP_1]) { async function renderGroups(groups: any[] = [GROUP_1]) {
setProcedure('admin.product.getGroups', { data: { groups } }) setProcedure('admin.product.getGroups', { data: { groups } })
const view = renderWithProviders(<ProductGroupings />, { auth: false }) const view = await renderAndFlush(<ProductGroupings />, { auth: false })
return { view } return { view }
} }
@ -49,22 +49,22 @@ describe('Product groupings list (AGRP-01..11)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('AGRP-01: shows the loading copy', () => { it('AGRP-01: shows the loading copy', async () => {
setProcedure('admin.product.getGroups', { mode: 'pending' }) setProcedure('admin.product.getGroups', { mode: 'pending' })
const view = renderWithProviders(<ProductGroupings />, { auth: false }) const view = renderWithProviders(<ProductGroupings />, { auth: false })
expect(view.getByText('Loading product groups...')).toBeTruthy() expect(view.getByText('Loading product groups...')).toBeTruthy()
}) })
it('AGRP-02: shows the error copy', () => { it('AGRP-02: shows the error copy', async () => {
setProcedure('admin.product.getGroups', { mode: 'error', error: new Error('no') }) setProcedure('admin.product.getGroups', { mode: 'error', error: new Error('no') })
const view = renderWithProviders(<ProductGroupings />, { auth: false }) const view = renderWithProviders(<ProductGroupings />, { auth: false })
expect(view.getByText('Error loading groups')).toBeTruthy() expect(await view.findByText('Error loading groups')).toBeTruthy()
}) })
it('AGRP-03: shows the empty state with the create action', () => { it('AGRP-03: shows the empty state with the create action', async () => {
const { view } = renderGroups([]) const { view } = await renderGroups([])
expect(view.getByText('No Groups Yet')).toBeTruthy() expect(view.getByText('No Groups Yet')).toBeTruthy()
expect( expect(
@ -73,8 +73,8 @@ describe('Product groupings list (AGRP-01..11)', () => {
expect(view.UNSAFE_getByType(MyTouchableOpacity)).toBeTruthy() expect(view.UNSAFE_getByType(MyTouchableOpacity)).toBeTruthy()
}) })
it('AGRP-04: renders the group name, description and product count', () => { it('AGRP-04: renders the group name, description and product count', async () => {
const { view } = renderGroups([GROUP_1]) const { view } = await renderGroups([GROUP_1])
expect(view.getByText('Breakfast')).toBeTruthy() expect(view.getByText('Breakfast')).toBeTruthy()
expect(view.getByText('Morning items')).toBeTruthy() expect(view.getByText('Morning items')).toBeTruthy()
@ -82,8 +82,8 @@ describe('Product groupings list (AGRP-01..11)', () => {
expect(view.getByText('Group Name')).toBeTruthy() expect(view.getByText('Group Name')).toBeTruthy()
}) })
it('AGRP-05: View Products currently only sets local state', () => { it('AGRP-05: View Products currently only sets local state', async () => {
const { view } = renderGroups([GROUP_1]) const { view } = await renderGroups([GROUP_1])
// The page imports BottomDialog but never renders it, so pressing the count // The page imports BottomDialog but never renders it, so pressing the count
// is inert beyond setViewProducts. // is inert beyond setViewProducts.
@ -93,8 +93,8 @@ describe('Product groupings list (AGRP-01..11)', () => {
expect(view.queryByText('Products in group')).toBeNull() expect(view.queryByText('Products in group')).toBeNull()
}) })
it('AGRP-06: Edit opens the edit route', () => { it('AGRP-06: Edit opens the edit route', async () => {
const { view } = renderGroups([GROUP_1]) const { view } = await renderGroups([GROUP_1])
fireEvent.press(icon(view, 'edit')) fireEvent.press(icon(view, 'edit'))
@ -102,7 +102,7 @@ describe('Product groupings list (AGRP-01..11)', () => {
}) })
it('AGRP-07: Delete asks for confirmation and Cancel makes no call', async () => { it('AGRP-07: Delete asks for confirmation and Cancel makes no call', async () => {
const { view } = renderGroups([GROUP_1]) const { view } = await renderGroups([GROUP_1])
fireEvent.press(icon(view, 'delete')) fireEvent.press(icon(view, 'delete'))
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
@ -119,7 +119,7 @@ describe('Product groupings list (AGRP-01..11)', () => {
}) })
it('AGRP-08: confirming Delete calls deleteGroup', async () => { it('AGRP-08: confirming Delete calls deleteGroup', async () => {
const { view } = renderGroups([GROUP_1]) const { view } = await renderGroups([GROUP_1])
fireEvent.press(icon(view, 'delete')) fireEvent.press(icon(view, 'delete'))
await confirmDelete(alertSpy) await confirmDelete(alertSpy)
@ -129,7 +129,7 @@ describe('Product groupings list (AGRP-01..11)', () => {
it('AGRP-09: a failed delete currently does not alert', async () => { it('AGRP-09: a failed delete currently does not alert', async () => {
setProcedure('admin.product.deleteGroup', { mode: 'error', error: new Error('no') }) setProcedure('admin.product.deleteGroup', { mode: 'error', error: new Error('no') })
const { view } = renderGroups([GROUP_1]) const { view } = await renderGroups([GROUP_1])
fireEvent.press(icon(view, 'delete')) fireEvent.press(icon(view, 'delete'))
await confirmDelete(alertSpy) await confirmDelete(alertSpy)
@ -138,18 +138,19 @@ describe('Product groupings list (AGRP-01..11)', () => {
expect(alertSpy.mock.calls.every((call) => call[0] !== 'Error')).toBe(true) expect(alertSpy.mock.calls.every((call) => call[0] !== 'Error')).toBe(true)
}) })
it('AGRP-10: the create FAB opens the create route', () => { it('AGRP-10: the create FAB opens the create route', async () => {
const { view } = renderGroups([]) const { view } = await renderGroups([])
fireEvent.press(view.UNSAFE_getByType(MyTouchableOpacity)) fireEvent.press(view.UNSAFE_getByType(MyTouchableOpacity))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-groupings/create') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-groupings/create')
}) })
it('AGRP-11: a refresh event keeps the list rendered', () => { it('AGRP-11: a refresh event keeps the list rendered', async () => {
const { view } = renderGroups([GROUP_1]) const { view } = await renderGroups([GROUP_1])
DeviceEventEmitter.emit('refresh_event') DeviceEventEmitter.emit('refresh_event')
await flush()
expect(view.getByText('Breakfast')).toBeTruthy() expect(view.getByText('Breakfast')).toBeTruthy()
expect(view.getByText('2 Products')).toBeTruthy() expect(view.getByText('2 Products')).toBeTruthy()

View file

@ -4,20 +4,20 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import { ImageUploaderNeo } from 'common-ui' import { ImageUploaderNeo } from 'common-ui'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
import AddTag from '@/app/(drawer)/dashboard/product-tags/add' import AddTag from '@/app/(drawer)/dashboard/product-tags/add'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput } from '../mocks/trpc-client' import { setProcedure, lastMutationInput, setRawFetchHandler } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
type View = ReturnType<typeof renderAdd>['view'] type View = Awaited<ReturnType<typeof renderAdd>>['view']
function renderAdd() { async function renderAdd() {
const view = renderWithProviders(<AddTag />, { auth: false }) const view = await renderAndFlush(<AddTag />, { auth: false })
return { view } return { view }
} }
@ -40,8 +40,8 @@ describe('Product tag add (ATAGA-01..05)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('ATAGA-01: renders the TagForm', () => { it('ATAGA-01: renders the TagForm', async () => {
const { view } = renderAdd() const { view } = await renderAdd()
expect(view.getByPlaceholderText('Enter tag name')).toBeTruthy() expect(view.getByPlaceholderText('Enter tag name')).toBeTruthy()
expect(view.getByText('Create Tag')).toBeTruthy() expect(view.getByText('Create Tag')).toBeTruthy()
@ -49,7 +49,7 @@ describe('Product tag add (ATAGA-01..05)', () => {
}) })
it('ATAGA-02: creates a tag with the form payload', async () => { it('ATAGA-02: creates a tag with the form payload', async () => {
const { view } = renderAdd() const { view } = await renderAdd()
fillName(view) fillName(view)
fireEvent.changeText(view.getByPlaceholderText('Enter tag description'), 'All chicken') fireEvent.changeText(view.getByPlaceholderText('Enter tag description'), 'All chicken')
@ -70,13 +70,13 @@ describe('Product tag add (ATAGA-01..05)', () => {
canceled: false, canceled: false,
assets: [{ uri: 'file:///tag.jpg', mimeType: 'image/jpeg', fileName: 'tag.jpg' }], assets: [{ uri: 'file:///tag.jpg', mimeType: 'image/jpeg', fileName: 'tag.jpg' }],
}) })
jest.spyOn(global, 'fetch').mockImplementation((async (url: any) => { setRawFetchHandler(async (_url, init) => {
if (String(url).startsWith('file://')) { if (init?.method === 'PUT') {
return { blob: async () => ({ size: 1 }) } return { ok: true, status: 200, text: async () => '' } as any
} }
return { ok: true, status: 200, text: async () => '' } return { ok: true, status: 200, blob: async () => ({ size: 1 }) } as any
}) as any) })
const { view } = renderAdd() const { view } = await renderAdd()
fillName(view) fillName(view)
const uploader = view.UNSAFE_getByType(ImageUploaderNeo) const uploader = view.UNSAFE_getByType(ImageUploaderNeo)
@ -97,25 +97,27 @@ describe('Product tag add (ATAGA-01..05)', () => {
mode: 'error', mode: 'error',
error: new Error('Tag exists'), error: new Error('Tag exists'),
}) })
const { view } = renderAdd() const { view } = await renderAdd()
fillName(view) fillName(view)
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Tag exists') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'Tag exists'))
}) })
it('ATAGA-05: success alerts and goes back on OK', async () => { it('ATAGA-05: success alerts and goes back on OK', async () => {
const { view } = renderAdd() const { view } = await renderAdd()
fillName(view) fillName(view)
await submit(view) await submit(view)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Success', 'Success',
'Tag created successfully', 'Tag created successfully',
expect.any(Array) expect.any(Array)
) )
)
const buttons = alertSpy.mock.calls.find((call) => call[0] === 'Success')[2] const buttons = alertSpy.mock.calls.find((call) => call[0] === 'Success')[2]
act(() => { act(() => {
buttons[0].onPress() buttons[0].onPress()

View file

@ -4,26 +4,28 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import { ImageUploaderNeo } from 'common-ui' import { ImageUploaderNeo } from 'common-ui'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
import EditTag from '@/app/(drawer)/dashboard/product-tags/edit/index' import EditTag from '@/app/(drawer)/dashboard/product-tags/edit/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
lastMutationInput, lastMutationInput,
procedureInvalidations, procedureInvalidations,
setRawFetchHandler,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { router, __setParams } from '../mocks/expo-router-mock' import { router, __setParams } from '../mocks/expo-router-mock'
import { TAG_1 } from '../fixtures' import { TAG_1 } from '../fixtures'
type View = ReturnType<typeof renderEdit>['view'] type View = Awaited<ReturnType<typeof renderEdit>>['view']
function renderEdit() { async function renderEdit() {
__setParams({ tagId: '1' }) __setParams({ tagId: '1' })
const view = renderWithProviders(<EditTag />, { auth: false }) const view = await renderAndFlush(<EditTag />, { auth: false })
await flush(2)
return { view } return { view }
} }
@ -46,22 +48,22 @@ describe('Product tag edit (ATAGE-01..07)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('ATAGE-01: shows the loading copy', () => { it('ATAGE-01: shows the loading copy', async () => {
setProcedure('admin.product.getProductTagById', { mode: 'pending' }) setProcedure('admin.product.getProductTagById', { mode: 'pending' })
const { view } = renderEdit() const { view } = await renderEdit()
expect(view.getByText('Loading tag...')).toBeTruthy() expect(view.getByText('Loading tag...')).toBeTruthy()
}) })
it('ATAGE-02: shows Tag not found', () => { it('ATAGE-02: shows Tag not found', async () => {
setProcedure('admin.product.getProductTagById', { data: { tag: null } }) setProcedure('admin.product.getProductTagById', { data: { tag: null } })
const { view } = renderEdit() const { view } = await renderEdit()
expect(view.getByText('Tag not found')).toBeTruthy() expect(view.getByText('Tag not found')).toBeTruthy()
}) })
it('ATAGE-03: prefills name, description, stores and products', () => { it('ATAGE-03: prefills name, description, stores and products', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
expect(view.getByPlaceholderText('Enter tag name').props.value).toBe('Chicken') expect(view.getByPlaceholderText('Enter tag name').props.value).toBe('Chicken')
expect(view.getByPlaceholderText('Enter tag description').props.value).toBe( expect(view.getByPlaceholderText('Enter tag description').props.value).toBe(
@ -73,7 +75,7 @@ describe('Product tag edit (ATAGE-01..07)', () => {
}) })
it('ATAGE-04: saving calls updateProductTag and refreshes', async () => { it('ATAGE-04: saving calls updateProductTag and refreshes', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
fillName(view) fillName(view)
await submit(view) await submit(view)
@ -88,15 +90,17 @@ describe('Product tag edit (ATAGE-01..07)', () => {
uploadUrls: [], uploadUrls: [],
}) })
expect(procedureInvalidations('admin.product.getProductTagById').length).toBeGreaterThan(0) expect(procedureInvalidations('admin.product.getProductTagById').length).toBeGreaterThan(0)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Success', 'Success',
'Tag updated successfully', 'Tag updated successfully',
expect.any(Array) expect.any(Array)
) )
)
}) })
it('ATAGE-05: removing the existing image sends imageUrl null', async () => { it('ATAGE-05: removing the existing image sends imageUrl null', async () => {
const { view } = renderEdit() const { view } = await renderEdit()
const uploader = view.UNSAFE_getByType(ImageUploaderNeo) const uploader = view.UNSAFE_getByType(ImageUploaderNeo)
act(() => { act(() => {
@ -113,13 +117,13 @@ describe('Product tag edit (ATAGE-01..07)', () => {
canceled: false, canceled: false,
assets: [{ uri: 'file:///tag.jpg', mimeType: 'image/jpeg', fileName: 'tag.jpg' }], assets: [{ uri: 'file:///tag.jpg', mimeType: 'image/jpeg', fileName: 'tag.jpg' }],
}) })
jest.spyOn(global, 'fetch').mockImplementation((async (url: any) => { setRawFetchHandler(async (_url, init) => {
if (String(url).startsWith('file://')) { if (init?.method === 'PUT') {
return { blob: async () => ({ size: 1 }) } return { ok: true, status: 200, text: async () => '' } as any
} }
return { ok: true, status: 200, text: async () => '' } return { ok: true, status: 200, blob: async () => ({ size: 1 }) } as any
}) as any) })
const { view } = renderEdit() const { view } = await renderEdit()
const uploader = view.UNSAFE_getByType(ImageUploaderNeo) const uploader = view.UNSAFE_getByType(ImageUploaderNeo)
act(() => { act(() => {
@ -140,11 +144,11 @@ describe('Product tag edit (ATAGE-01..07)', () => {
mode: 'error', mode: 'error',
error: new Error('Tag name taken'), error: new Error('Tag name taken'),
}) })
const { view } = renderEdit() const { view } = await renderEdit()
fillName(view) fillName(view)
await submit(view) await submit(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Tag name taken') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'Tag name taken'))
}) })
}) })

View file

@ -8,7 +8,7 @@ import { act, fireEvent, within } from '@testing-library/react-native'
import DraggableFlatList from 'react-native-draggable-flatlist' import DraggableFlatList from 'react-native-draggable-flatlist'
import TagOrders from '@/app/(drawer)/dashboard/product-tags/order' import TagOrders from '@/app/(drawer)/dashboard/product-tags/order'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -18,11 +18,11 @@ import {
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { TAGS } from '../fixtures' import { TAGS } from '../fixtures'
type View = ReturnType<typeof renderOrder>['view'] type View = Awaited<ReturnType<typeof renderOrder>>['view']
const CONSTANTS = [{ key: 'tagsOrder', value: '2,1' }] const CONSTANTS = [{ key: 'tagsOrder', value: '2,1' }]
function renderOrder( async function renderOrder(
opts: { tags?: any[]; constants?: any[] | null } = {} opts: { tags?: any[]; constants?: any[] | null } = {}
) { ) {
const tags = opts.tags ?? TAGS const tags = opts.tags ?? TAGS
@ -31,7 +31,8 @@ function renderOrder(
if (constants !== null) { if (constants !== null) {
setProcedure('admin.region.getRegionConstants', { data: constants }) setProcedure('admin.region.getRegionConstants', { data: constants })
} }
const view = renderWithProviders(<TagOrders />, { auth: false }) const view = await renderAndFlush(<TagOrders />, { auth: false })
await flush()
return { view } return { view }
} }
@ -60,31 +61,31 @@ describe('Product tag order (ATAGO-01..08)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('ATAGO-01: shows the loading copy', () => { it('ATAGO-01: shows the loading copy', async () => {
setProcedure('admin.region.getRegionConstants', { mode: 'pending' }) setProcedure('admin.region.getRegionConstants', { mode: 'pending' })
const view = renderWithProviders(<TagOrders />, { auth: false }) const view = renderWithProviders(<TagOrders />, { auth: false })
expect(view.getByText('Loading order...')).toBeTruthy() expect(view.getByText('Loading order...')).toBeTruthy()
}) })
it('ATAGO-02: shows the error state with Go Back', () => { it('ATAGO-02: shows the error state with Go Back', async () => {
setProcedure('admin.region.getRegionConstants', { mode: 'error', error: new Error('no') }) setProcedure('admin.region.getRegionConstants', { mode: 'error', error: new Error('no') })
const view = renderWithProviders(<TagOrders />, { auth: false }) const view = renderWithProviders(<TagOrders />, { auth: false })
expect(view.getByText('Error')).toBeTruthy() expect(await view.findByText('Error')).toBeTruthy()
expect(view.getByText('Failed to load order')).toBeTruthy() expect(view.getByText('Failed to load order')).toBeTruthy()
fireEvent.press(view.getByText('Go Back')) fireEvent.press(view.getByText('Go Back'))
expect(router.back).toHaveBeenCalled() expect(router.back).toHaveBeenCalled()
}) })
it('ATAGO-03: renders tags in tagsOrder order, unknown tags after', () => { it('ATAGO-03: renders tags in tagsOrder order, unknown tags after', async () => {
const { view } = renderOrder() const { view } = await renderOrder()
expect(renderedNames(view)).toEqual(['Veg', 'Chicken']) expect(renderedNames(view)).toEqual(['Veg', 'Chicken'])
}) })
it('ATAGO-04: dragging updates the rendered order', async () => { it('ATAGO-04: dragging updates the rendered order', async () => {
const { view } = renderOrder() const { view } = await renderOrder()
await reorder(view, [ await reorder(view, [
{ id: 1, tagName: 'Chicken', imageUrl: null }, { id: 1, tagName: 'Chicken', imageUrl: null },
@ -95,7 +96,7 @@ describe('Product tag order (ATAGO-01..08)', () => {
}) })
it('ATAGO-05: saving writes the new tagsOrder', async () => { it('ATAGO-05: saving writes the new tagsOrder', async () => {
const { view } = renderOrder() const { view } = await renderOrder()
await reorder(view, [ await reorder(view, [
{ id: 1, tagName: 'Chicken', imageUrl: null }, { id: 1, tagName: 'Chicken', imageUrl: null },
@ -112,8 +113,8 @@ describe('Product tag order (ATAGO-01..08)', () => {
expect(alertSpy).toHaveBeenCalledWith('Success', 'Tag order updated successfully!') expect(alertSpy).toHaveBeenCalledWith('Success', 'Tag order updated successfully!')
}) })
it('ATAGO-06: with no changes Save is disabled and saves nothing', () => { it('ATAGO-06: with no changes Save is disabled and saves nothing', async () => {
const { view } = renderOrder() const { view } = await renderOrder()
fireEvent.press(view.getByText('Save')) fireEvent.press(view.getByText('Save'))
@ -125,7 +126,7 @@ describe('Product tag order (ATAGO-01..08)', () => {
mode: 'error', mode: 'error',
error: new Error('no'), error: new Error('no'),
}) })
const { view } = renderOrder() const { view } = await renderOrder()
await reorder(view, [ await reorder(view, [
{ id: 1, tagName: 'Chicken', imageUrl: null }, { id: 1, tagName: 'Chicken', imageUrl: null },
@ -142,8 +143,8 @@ describe('Product tag order (ATAGO-01..08)', () => {
) )
}) })
it('ATAGO-08: shows the empty copy when there are no tags', () => { it('ATAGO-08: shows the empty copy when there are no tags', async () => {
const { view } = renderOrder({ tags: [] }) const { view } = await renderOrder({ tags: [] })
expect(view.getByText('No tags available')).toBeTruthy() expect(view.getByText('No tags available')).toBeTruthy()
}) })

View file

@ -6,73 +6,73 @@ import React from 'react'
import { fireEvent } from '@testing-library/react-native' import { fireEvent } from '@testing-library/react-native'
import ProductTags from '@/app/(drawer)/dashboard/product-tags/index' import ProductTags from '@/app/(drawer)/dashboard/product-tags/index'
import { renderWithProviders } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client' import { setProcedure } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { TAGS, TAG_1 } from '../fixtures' import { TAGS, TAG_1 } from '../fixtures'
type View = ReturnType<typeof renderTags>['view'] type View = Awaited<ReturnType<typeof renderTags>>['view']
function renderTags(tags: any[] = TAGS) { async function renderTags(tags: any[] = TAGS) {
setProcedure('admin.product.getProductTags', { data: { tags } }) setProcedure('admin.product.getProductTags', { data: { tags } })
const view = renderWithProviders(<ProductTags />, { auth: false }) const view = await renderAndFlush(<ProductTags />, { auth: false })
return { view } return { view }
} }
describe('Product tags list (ATAG-01..08)', () => { describe('Product tags list (ATAG-01..08)', () => {
beforeEach(() => resetAllMocks()) beforeEach(() => resetAllMocks())
it('ATAG-01: shows the loading copy', () => { it('ATAG-01: shows the loading copy', async () => {
setProcedure('admin.product.getProductTags', { mode: 'pending' }) setProcedure('admin.product.getProductTags', { mode: 'pending' })
const view = renderWithProviders(<ProductTags />, { auth: false }) const view = renderWithProviders(<ProductTags />, { auth: false })
expect(view.getByText('Loading tags...')).toBeTruthy() expect(view.getByText('Loading tags...')).toBeTruthy()
}) })
it('ATAG-02: shows the error state with Retry', () => { it('ATAG-02: shows the error state with Retry', async () => {
setProcedure('admin.product.getProductTags', { mode: 'error', error: new Error('boom') }) setProcedure('admin.product.getProductTags', { mode: 'error', error: new Error('boom') })
const view = renderWithProviders(<ProductTags />, { auth: false }) const view = renderWithProviders(<ProductTags />, { auth: false })
expect(view.getByText('Error')).toBeTruthy() expect(await view.findByText('Error')).toBeTruthy()
expect(view.getByText('Retry')).toBeTruthy() expect(view.getByText('Retry')).toBeTruthy()
fireEvent.press(view.getByText('Retry')) fireEvent.press(view.getByText('Retry'))
}) })
it('ATAG-03: shows the empty state alongside the add action', () => { it('ATAG-03: shows the empty state alongside the add action', async () => {
const { view } = renderTags([]) const { view } = await renderTags([])
expect(view.getByText('No tags yet')).toBeTruthy() expect(view.getByText('No tags yet')).toBeTruthy()
expect(view.getByText('Create your first product tag')).toBeTruthy() expect(view.getByText('Create your first product tag')).toBeTruthy()
expect(view.getByText('Add New Tag')).toBeTruthy() expect(view.getByText('Add New Tag')).toBeTruthy()
}) })
it('ATAG-04: renders name, description and the dashboard badge', () => { it('ATAG-04: renders name, description and the dashboard badge', async () => {
const { view } = renderTags([TAG_1]) const { view } = await renderTags([TAG_1])
expect(view.getByText('Chicken')).toBeTruthy() expect(view.getByText('Chicken')).toBeTruthy()
expect(view.getByText('All chicken items')).toBeTruthy() expect(view.getByText('All chicken items')).toBeTruthy()
expect(view.getByText('Dashboard Tag')).toBeTruthy() expect(view.getByText('Dashboard Tag')).toBeTruthy()
}) })
it('ATAG-05: Tag Orders opens the ordering route', () => { it('ATAG-05: Tag Orders opens the ordering route', async () => {
const { view } = renderTags() const { view } = await renderTags()
fireEvent.press(view.getByText('Tag Orders')) fireEvent.press(view.getByText('Tag Orders'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-tags/order') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-tags/order')
}) })
it('ATAG-06: Add New Tag opens the add route', () => { it('ATAG-06: Add New Tag opens the add route', async () => {
const { view } = renderTags() const { view } = await renderTags()
fireEvent.press(view.getByText('Add New Tag')) fireEvent.press(view.getByText('Add New Tag'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-tags/add') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/product-tags/add')
}) })
it('ATAG-07: a refresh event keeps the list rendered', () => { it('ATAG-07: a refresh event keeps the list rendered', async () => {
const { view } = renderTags() const { view } = await renderTags()
const { DeviceEventEmitter } = require('react-native') const { DeviceEventEmitter } = require('react-native')
DeviceEventEmitter.emit('refresh_event') DeviceEventEmitter.emit('refresh_event')
@ -81,9 +81,9 @@ describe('Product tags list (ATAG-01..08)', () => {
expect(view.getByText('Veg')).toBeTruthy() expect(view.getByText('Veg')).toBeTruthy()
}) })
it('ATAG-08: a long tag name renders', () => { it('ATAG-08: a long tag name renders', async () => {
const longName = 'Tag '.repeat(60).trim() const longName = 'Tag '.repeat(60).trim()
const { view } = renderTags([{ ...TAG_1, tagName: longName }]) const { view } = await renderTags([{ ...TAG_1, tagName: longName }])
expect(view.getByText(longName)).toBeTruthy() expect(view.getByText(longName)).toBeTruthy()
}) })

View file

@ -7,7 +7,7 @@ import { DeviceEventEmitter, RefreshControl } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent } from '@testing-library/react-native'
import Products from '@/app/(drawer)/dashboard/products/index' import Products from '@/app/(drawer)/dashboard/products/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client' import { setProcedure } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
@ -43,26 +43,26 @@ const navMock = require('@react-navigation/native') as {
__focusCallbacks: Array<() => any> __focusCallbacks: Array<() => any>
} }
function renderProducts() { async function renderProducts() {
return renderWithProviders(<Products />, { auth: 'in' }) return renderAndFlush(<Products />, { auth: 'in' })
} }
const search = (view: ReturnType<typeof renderProducts>) => const search = (view: Awaited<ReturnType<typeof renderProducts>>) =>
view.getByPlaceholderText('Search products...') view.getByPlaceholderText('Search products...')
describe('Product list (APLIST-01..26)', () => { describe('Product list (APLIST-01..26)', () => {
beforeEach(() => resetAllMocks()) beforeEach(() => resetAllMocks())
it('APLIST-01: shows the loading copy', () => { it('APLIST-01: shows the loading copy', async () => {
setProcedure('admin.product.getProducts', { mode: 'pending' }) setProcedure('admin.product.getProducts', { mode: 'pending' })
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('Loading products...')).toBeTruthy() expect(view.getByText('Loading products...')).toBeTruthy()
}) })
it('APLIST-02: shows the error copy and a Retry action', () => { it('APLIST-02: shows the error copy and a Retry action', async () => {
setProcedure('admin.product.getProducts', { mode: 'error', error: new Error('boom') }) setProcedure('admin.product.getProducts', { mode: 'error', error: new Error('boom') })
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('Error loading products')).toBeTruthy() expect(view.getByText('Error loading products')).toBeTruthy()
expect(view.getByText('Retry')).toBeTruthy() expect(view.getByText('Retry')).toBeTruthy()
@ -72,16 +72,16 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.getByText('Error loading products')).toBeTruthy() expect(view.getByText('Error loading products')).toBeTruthy()
}) })
it('APLIST-03: renders the empty state', () => { it('APLIST-03: renders the empty state', async () => {
setProcedure('admin.product.getProducts', { data: { products: [], count: 0 } }) setProcedure('admin.product.getProducts', { data: { products: [], count: 0 } })
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('No products found')).toBeTruthy() expect(view.getByText('No products found')).toBeTruthy()
expect(view.getByText('Start by adding your first product')).toBeTruthy() expect(view.getByText('Start by adding your first product')).toBeTruthy()
}) })
it('APLIST-04: renders a populated row with name, description, variant count and image', () => { it('APLIST-04: renders a populated row with name, description, variant count and image', async () => {
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('Chicken Breast')).toBeTruthy() expect(view.getByText('Chicken Breast')).toBeTruthy()
expect(view.getByText('Tender boneless breast')).toBeTruthy() expect(view.getByText('Tender boneless breast')).toBeTruthy()
@ -90,22 +90,22 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.getAllByLabelText('chicken.jpg').length).toBeGreaterThan(0) expect(view.getAllByLabelText('chicken.jpg').length).toBeGreaterThan(0)
}) })
it('APLIST-05: renders a placeholder icon when a product has no image', () => { it('APLIST-05: renders a placeholder icon when a product has no image', async () => {
const view = renderProducts() const view = await renderProducts()
expect(view.getByTestId('product-image-placeholder-7')).toBeTruthy() expect(view.getByTestId('product-image-placeholder-7')).toBeTruthy()
expect(view.queryByTestId('product-image-placeholder-2')).toBeNull() expect(view.queryByTestId('product-image-placeholder-2')).toBeNull()
}) })
it('APLIST-06: shows the GLOBAL badge for global products', () => { it('APLIST-06: shows the GLOBAL badge for global products', async () => {
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('GLOBAL')).toBeTruthy() expect(view.getByText('GLOBAL')).toBeTruthy()
}) })
it('APLIST-07: shows green "In" when all SKUs are in stock', () => { it('APLIST-07: shows green "In" when all SKUs are in stock', async () => {
setProcedure('admin.product.getProducts', { data: { products: [P_CHICKEN], count: 1 } }) setProcedure('admin.product.getProducts', { data: { products: [P_CHICKEN], count: 1 } })
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('In')).toBeTruthy() expect(view.getByText('In')).toBeTruthy()
expect(view.queryByText('Partial')).toBeNull() expect(view.queryByText('Partial')).toBeNull()
@ -113,35 +113,35 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.getByText('2 Variants')).toBeTruthy() expect(view.getByText('2 Variants')).toBeTruthy()
}) })
it('APLIST-08: shows red "Out" and the out-of-stock variant count', () => { it('APLIST-08: shows red "Out" and the out-of-stock variant count', async () => {
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('Out')).toBeTruthy() expect(view.getByText('Out')).toBeTruthy()
expect(view.getByText('1 Variants · 1 out')).toBeTruthy() expect(view.getByText('1 Variants · 1 out')).toBeTruthy()
}) })
it('APLIST-09: shows amber "Partial" for mixed stock', () => { it('APLIST-09: shows amber "Partial" for mixed stock', async () => {
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('Partial')).toBeTruthy() expect(view.getByText('Partial')).toBeTruthy()
expect(view.getByText('2 Variants · 1 out')).toBeTruthy() expect(view.getByText('2 Variants · 1 out')).toBeTruthy()
}) })
it('APLIST-10: treats a product with zero SKUs as in stock', () => { it('APLIST-10: treats a product with zero SKUs as in stock', async () => {
setProcedure('admin.product.getProducts', { setProcedure('admin.product.getProducts', {
data: { data: {
products: [{ ...P_CUCUMBER, id: 20, name: 'Empty SKUs', skus: [] }], products: [{ ...P_CUCUMBER, id: 20, name: 'Empty SKUs', skus: [] }],
count: 1, count: 1,
}, },
}) })
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('0 Variants')).toBeTruthy() expect(view.getByText('0 Variants')).toBeTruthy()
expect(view.getByText('In')).toBeTruthy() expect(view.getByText('In')).toBeTruthy()
}) })
it('APLIST-11: filters by product name', () => { it('APLIST-11: filters by product name', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.changeText(search(view), 'Chicken') fireEvent.changeText(search(view), 'Chicken')
@ -149,8 +149,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.queryByText('Cucumber')).toBeNull() expect(view.queryByText('Cucumber')).toBeNull()
}) })
it('APLIST-12: filters by short description', () => { it('APLIST-12: filters by short description', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.changeText(search(view), 'boneless') fireEvent.changeText(search(view), 'boneless')
@ -158,8 +158,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.queryByText('Cucumber')).toBeNull() expect(view.queryByText('Cucumber')).toBeNull()
}) })
it('APLIST-13: searches case-insensitively', () => { it('APLIST-13: searches case-insensitively', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.changeText(search(view), 'cHicKeN') fireEvent.changeText(search(view), 'cHicKeN')
@ -167,8 +167,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.queryByText('Mutton')).toBeNull() expect(view.queryByText('Mutton')).toBeNull()
}) })
it('APLIST-14: shows the no-match copy and Clear Filters resets everything', () => { it('APLIST-14: shows the no-match copy and Clear Filters resets everything', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.changeText(search(view), 'zzzz') fireEvent.changeText(search(view), 'zzzz')
expect(view.getByText('No products match your filters')).toBeTruthy() expect(view.getByText('No products match your filters')).toBeTruthy()
@ -179,8 +179,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(search(view).props.value).toBe('') expect(search(view).props.value).toBe('')
}) })
it('APLIST-15: the In Stock filter keeps only all-in-stock products', () => { it('APLIST-15: the In Stock filter keeps only all-in-stock products', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.press(view.getByText('In Stock (4)')) fireEvent.press(view.getByText('In Stock (4)'))
@ -189,8 +189,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.queryByText('Mixed Stock')).toBeNull() expect(view.queryByText('Mixed Stock')).toBeNull()
}) })
it('APLIST-16: the Out of Stock filter keeps partial and fully-out products', () => { it('APLIST-16: the Out of Stock filter keeps partial and fully-out products', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.press(view.getByText('Out of Stock (2)')) fireEvent.press(view.getByText('Out of Stock (2)'))
@ -199,8 +199,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.queryByText('Chicken Breast')).toBeNull() expect(view.queryByText('Chicken Breast')).toBeNull()
}) })
it('APLIST-17: the Global filter keeps only global products', () => { it('APLIST-17: the Global filter keeps only global products', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.press(view.getByText('Global (1)')) fireEvent.press(view.getByText('Global (1)'))
@ -209,8 +209,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.queryByText('Cucumber')).toBeNull() expect(view.queryByText('Cucumber')).toBeNull()
}) })
it('APLIST-18: filter counts match the products', () => { it('APLIST-18: filter counts match the products', async () => {
const view = renderProducts() const view = await renderProducts()
expect(view.getByText('All (6)')).toBeTruthy() expect(view.getByText('All (6)')).toBeTruthy()
expect(view.getByText('In Stock (4)')).toBeTruthy() expect(view.getByText('In Stock (4)')).toBeTruthy()
@ -218,8 +218,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.getByText('Global (1)')).toBeTruthy() expect(view.getByText('Global (1)')).toBeTruthy()
}) })
it('APLIST-19: Clear Filters clears the search and resets the filter to All', () => { it('APLIST-19: Clear Filters clears the search and resets the filter to All', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.press(view.getByText('Out of Stock (2)')) fireEvent.press(view.getByText('Out of Stock (2)'))
fireEvent.changeText(search(view), 'zzz') fireEvent.changeText(search(view), 'zzz')
@ -230,24 +230,24 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.getByText('All (6)')).toBeTruthy() expect(view.getByText('All (6)')).toBeTruthy()
}) })
it('APLIST-20: View opens the product detail route', () => { it('APLIST-20: View opens the product detail route', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.press(view.getAllByText('View')[0]) fireEvent.press(view.getAllByText('View')[0])
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/detail/2') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/detail/2')
}) })
it('APLIST-21: Edit opens the edit route with the product id', () => { it('APLIST-21: Edit opens the edit route with the product id', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.press(view.getAllByText('Edit')[0]) fireEvent.press(view.getAllByText('Edit')[0])
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit?id=2') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit?id=2')
}) })
it('APLIST-22: Stock opens the variant stock dialog for that product', () => { it('APLIST-22: Stock opens the variant stock dialog for that product', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.press(view.getAllByText('Stock')[0]) fireEvent.press(view.getAllByText('Stock')[0])
@ -255,8 +255,8 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.getByTestId('variant-stock-12')).toBeTruthy() expect(view.getByTestId('variant-stock-12')).toBeTruthy()
}) })
it('APLIST-23: Add Product opens the create route', () => { it('APLIST-23: Add Product opens the create route', async () => {
const view = renderProducts() const view = await renderProducts()
fireEvent.press(view.getByTestId('add-product-button')) fireEvent.press(view.getByTestId('add-product-button'))
@ -265,7 +265,7 @@ describe('Product list (APLIST-01..26)', () => {
it('APLIST-24: pull-to-refresh is wired to the refresh path', async () => { it('APLIST-24: pull-to-refresh is wired to the refresh path', async () => {
const addListener = jest.spyOn(DeviceEventEmitter, 'addListener') const addListener = jest.spyOn(DeviceEventEmitter, 'addListener')
const view = renderProducts() const view = await renderProducts()
const refreshListener = addListener.mock.calls.find(([event]) => event === REFRESH_EVENT)?.[1] const refreshListener = addListener.mock.calls.find(([event]) => event === REFRESH_EVENT)?.[1]
expect(typeof refreshListener).toBe('function') expect(typeof refreshListener).toBe('function')
@ -280,7 +280,7 @@ describe('Product list (APLIST-01..26)', () => {
}) })
it('APLIST-25: a focus refetches through the marked data fetcher', async () => { it('APLIST-25: a focus refetches through the marked data fetcher', async () => {
const view = renderProducts() const view = await renderProducts()
// The screen registers a focus callback; the first focus skips the refetch // The screen registers a focus callback; the first focus skips the refetch
// (mount already fetched), the next one invokes it. Refetch itself is an // (mount already fetched), the next one invokes it. Refetch itself is an
@ -294,14 +294,14 @@ describe('Product list (APLIST-01..26)', () => {
expect(view.getByText('Chicken Breast')).toBeTruthy() expect(view.getByText('Chicken Breast')).toBeTruthy()
}) })
it('APLIST-26: renders a 100+ product list without crashing', () => { it('APLIST-26: renders a 100+ product list without crashing', async () => {
const many = Array.from({ length: 120 }, (_, index) => ({ const many = Array.from({ length: 120 }, (_, index) => ({
...P_CHICKEN, ...P_CHICKEN,
id: 1000 + index, id: 1000 + index,
name: `Product ${index + 1}`, name: `Product ${index + 1}`,
})) }))
setProcedure('admin.product.getProducts', { data: { products: many, count: many.length } }) setProcedure('admin.product.getProducts', { data: { products: many, count: many.length } })
const view = renderProducts() const view = await renderProducts()
// Virtualised: only the first window is mounted, but the list is stable. // Virtualised: only the first window is mounted, but the list is stable.
expect(view.getByText('Product 1')).toBeTruthy() expect(view.getByText('Product 1')).toBeTruthy()

View file

@ -5,11 +5,11 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, RefreshControl } from 'react-native' import { Alert, RefreshControl } from 'react-native'
import { fireEvent, act } from '@testing-library/react-native' import { fireEvent, act, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import RebalanceOrders from '@/app/(drawer)/dashboard/rebalance-orders/index' import RebalanceOrders from '@/app/(drawer)/dashboard/rebalance-orders/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client' import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
import { SLOT_1 } from '../fixtures' import { SLOT_1 } from '../fixtures'
@ -18,10 +18,10 @@ const HOUR = 60 * 60 * 1000
const iso = (offset: number) => new Date(Date.now() + offset).toISOString() const iso = (offset: number) => new Date(Date.now() + offset).toISOString()
function renderRebalance() { function renderRebalance() {
return renderWithProviders(<RebalanceOrders />, { auth: 'in' }) return renderAndFlush(<RebalanceOrders />, { auth: 'in' })
} }
function rebalanceButton(view: ReturnType<typeof renderRebalance>) { function rebalanceButton(view: Awaited<ReturnType<typeof renderRebalance>>) {
return view.getByTestId('rebalance-button') return view.getByTestId('rebalance-button')
} }
@ -37,19 +37,20 @@ describe('Rebalance orders (AREB-01..13)', () => {
it('AREB-01: shows the loading copy', () => { it('AREB-01: shows the loading copy', () => {
setProcedure('admin.slots.getAll', { mode: 'pending' }) setProcedure('admin.slots.getAll', { mode: 'pending' })
const view = renderRebalance() const view = renderWithProviders(<RebalanceOrders />, { auth: 'in' })
// Loading assertions stay synchronous: the query never settles.
expect(view.getByText('Loading slots...')).toBeTruthy() expect(view.getByText('Loading slots...')).toBeTruthy()
}) })
it('AREB-02: shows the empty copy when there are no upcoming slots', () => { it('AREB-02: shows the empty copy when there are no upcoming slots', async () => {
setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } }) setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } })
const view = renderRebalance() const view = await renderRebalance()
expect(view.getByText('No upcoming slots available for rebalancing.')).toBeTruthy() expect(view.getByText('No upcoming slots available for rebalancing.')).toBeTruthy()
}) })
it('AREB-03: past slots are filtered out', () => { it('AREB-03: past slots are filtered out', async () => {
setProcedure('admin.slots.getAll', { setProcedure('admin.slots.getAll', {
data: { data: {
slots: [ slots: [
@ -59,14 +60,14 @@ describe('Rebalance orders (AREB-01..13)', () => {
count: 2, count: 2,
}, },
}) })
const view = renderRebalance() const view = await renderRebalance()
expect(view.queryByText('Slot #1700')).toBeNull() expect(view.queryByText('Slot #1700')).toBeNull()
expect(view.getByText('Slot #1849')).toBeTruthy() expect(view.getByText('Slot #1849')).toBeTruthy()
}) })
it('AREB-04: renders upcoming slot id, delivery/freeze and active status', () => { it('AREB-04: renders upcoming slot id, delivery/freeze and active status', async () => {
const view = renderRebalance() const view = await renderRebalance()
expect(view.getByText('Slot #1849')).toBeTruthy() expect(view.getByText('Slot #1849')).toBeTruthy()
expect(view.getByText('ID: 1849')).toBeTruthy() expect(view.getByText('ID: 1849')).toBeTruthy()
@ -76,7 +77,7 @@ describe('Rebalance orders (AREB-01..13)', () => {
expect(view.getAllByText('Inactive').length).toBeGreaterThanOrEqual(1) expect(view.getAllByText('Inactive').length).toBeGreaterThanOrEqual(1)
}) })
it('AREB-05: more than two products shows "+N more" and opens the dialog', () => { it('AREB-05: more than two products shows "+N more" and opens the dialog', async () => {
setProcedure('admin.slots.getAll', { setProcedure('admin.slots.getAll', {
data: { data: {
slots: [ slots: [
@ -93,37 +94,41 @@ describe('Rebalance orders (AREB-01..13)', () => {
count: 1, count: 1,
}, },
}) })
const view = renderRebalance() const view = await renderRebalance()
expect(view.getByText('+2 more')).toBeTruthy() expect(view.getByText('+2 more')).toBeTruthy()
fireEvent.press(view.getByText('+2 more')) fireEvent.press(view.getByText('+2 more'))
expect(view.getByText('All Products')).toBeTruthy() expect(view.getByText('All Products')).toBeTruthy()
}) })
it('AREB-06: selecting and deselecting a slot toggles the selection', () => { it('AREB-06: selecting and deselecting a slot toggles the selection', async () => {
const view = renderRebalance() const view = await renderRebalance()
fireEvent.press(view.getByTestId('rebalance-slot-1849')) fireEvent.press(view.getByTestId('rebalance-slot-1849'))
fireEvent.press(rebalanceButton(view)) fireEvent.press(rebalanceButton(view))
await waitFor(() =>
expect(lastMutationInput('admin.order.rebalanceSlots')).toEqual({ slotIds: [1849] }) expect(lastMutationInput('admin.order.rebalanceSlots')).toEqual({ slotIds: [1849] })
)
// Deselect the slot: the disabled button can no longer submit. // Deselect the slot: the disabled button can no longer submit.
fireEvent.press(view.getByTestId('rebalance-slot-1849')) fireEvent.press(view.getByTestId('rebalance-slot-1849'))
fireEvent.press(rebalanceButton(view)) fireEvent.press(rebalanceButton(view))
await flush(2)
expect(procedureMutationCalls('admin.order.rebalanceSlots')).toHaveLength(1) expect(procedureMutationCalls('admin.order.rebalanceSlots')).toHaveLength(1)
}) })
it('AREB-07: with no selection the rebalance button is disabled', () => { it('AREB-07: with no selection the rebalance button is disabled', async () => {
const view = renderRebalance() const view = await renderRebalance()
expect(rebalanceButton(view).props.accessibilityState?.disabled).toBe(true) expect(rebalanceButton(view).props.accessibilityState?.disabled).toBe(true)
fireEvent.press(rebalanceButton(view)) fireEvent.press(rebalanceButton(view))
await flush(2)
expect(procedureMutationCalls('admin.order.rebalanceSlots')).toHaveLength(0) expect(procedureMutationCalls('admin.order.rebalanceSlots')).toHaveLength(0)
}) })
it('AREB-08: rebalancing alerts and sends the selected slot ids', () => { it('AREB-08: rebalancing alerts and sends the selected slot ids', async () => {
const view = renderRebalance() const view = await renderRebalance()
fireEvent.press(view.getByTestId('rebalance-slot-1849')) fireEvent.press(view.getByTestId('rebalance-slot-1849'))
fireEvent.press(rebalanceButton(view)) fireEvent.press(rebalanceButton(view))
@ -133,31 +138,35 @@ describe('Rebalance orders (AREB-01..13)', () => {
'Please wait while we rebalance the selected slots.', 'Please wait while we rebalance the selected slots.',
[{ text: 'OK' }] [{ text: 'OK' }]
) )
await waitFor(() =>
expect(lastMutationInput('admin.order.rebalanceSlots')).toEqual({ slotIds: [1849] }) expect(lastMutationInput('admin.order.rebalanceSlots')).toEqual({ slotIds: [1849] })
)
}) })
it('AREB-09: a successful rebalance shows "Rebalance Complete"', async () => { it('AREB-09: a successful rebalance shows "Rebalance Complete"', async () => {
const view = renderRebalance() const view = await renderRebalance()
fireEvent.press(view.getByTestId('rebalance-slot-1849')) fireEvent.press(view.getByTestId('rebalance-slot-1849'))
fireEvent.press(rebalanceButton(view)) fireEvent.press(rebalanceButton(view))
await flush()
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Rebalance Complete', 'Slots have been rebalanced.') expect(alertSpy).toHaveBeenCalledWith('Rebalance Complete', 'Slots have been rebalanced.')
)
}) })
it('AREB-10: a failed rebalance still alerts on settle', async () => { it('AREB-10: a failed rebalance still alerts on settle', async () => {
setProcedure('admin.order.rebalanceSlots', { mode: 'error', error: new Error('boom') }) setProcedure('admin.order.rebalanceSlots', { mode: 'error', error: new Error('boom') })
const view = renderRebalance() const view = await renderRebalance()
fireEvent.press(view.getByTestId('rebalance-slot-1849')) fireEvent.press(view.getByTestId('rebalance-slot-1849'))
fireEvent.press(rebalanceButton(view)) fireEvent.press(rebalanceButton(view))
await flush()
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Rebalance Complete', 'Slots have been rebalanced.') expect(alertSpy).toHaveBeenCalledWith('Rebalance Complete', 'Slots have been rebalanced.')
)
}) })
it('AREB-11: the products dialog lists every product name', () => { it('AREB-11: the products dialog lists every product name', async () => {
setProcedure('admin.slots.getAll', { setProcedure('admin.slots.getAll', {
data: { data: {
slots: [ slots: [
@ -173,7 +182,7 @@ describe('Rebalance orders (AREB-01..13)', () => {
count: 1, count: 1,
}, },
}) })
const view = renderRebalance() const view = await renderRebalance()
fireEvent.press(view.getByText('+1 more')) fireEvent.press(view.getByText('+1 more'))
@ -184,7 +193,7 @@ describe('Rebalance orders (AREB-01..13)', () => {
}) })
it('AREB-12: pull to refresh runs the refresh handler', async () => { it('AREB-12: pull to refresh runs the refresh handler', async () => {
const view = renderRebalance() const view = await renderRebalance()
const refreshControl = view.UNSAFE_getByType(RefreshControl) const refreshControl = view.UNSAFE_getByType(RefreshControl)
expect(typeof refreshControl.props.onRefresh).toBe('function') expect(typeof refreshControl.props.onRefresh).toBe('function')
@ -198,13 +207,15 @@ describe('Rebalance orders (AREB-01..13)', () => {
expect(view.getByText('Slot #1849')).toBeTruthy() expect(view.getByText('Slot #1849')).toBeTruthy()
}) })
it('AREB-13: multiple selected slots are all sent in the payload', () => { it('AREB-13: multiple selected slots are all sent in the payload', async () => {
const view = renderRebalance() const view = await renderRebalance()
fireEvent.press(view.getByTestId('rebalance-slot-1849')) fireEvent.press(view.getByTestId('rebalance-slot-1849'))
fireEvent.press(view.getByTestId('rebalance-slot-1850')) fireEvent.press(view.getByTestId('rebalance-slot-1850'))
fireEvent.press(rebalanceButton(view)) fireEvent.press(rebalanceButton(view))
await waitFor(() =>
expect(lastMutationInput('admin.order.rebalanceSlots')).toEqual({ slotIds: [1849, 1850] }) expect(lastMutationInput('admin.order.rebalanceSlots')).toEqual({ slotIds: [1849, 1850] })
)
}) })
}) })

View file

@ -7,7 +7,7 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, TouchableOpacity } from 'react-native' import { Alert, TouchableOpacity } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import SendNotifications from '@/app/(drawer)/dashboard/send-notifications/index' import SendNotifications from '@/app/(drawer)/dashboard/send-notifications/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, flush } from '../helpers/test-utils'
@ -40,20 +40,29 @@ describe('Send notifications (ANOTIF-01..16)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
function renderPage() { async function renderPage() {
return renderWithProviders(<SendNotifications />, { auth: 'in' }) const view = renderWithProviders(<SendNotifications />, { auth: 'in' })
await flush()
return view
} }
function fillForm(view: ReturnType<typeof renderPage>, title = 'Hello', message = 'World') { type View = Awaited<ReturnType<typeof renderPage>>
function fillForm(view: View, title = 'Hello', message = 'World') {
fireEvent.changeText(view.getByPlaceholderText(TITLE_PLACEHOLDER), title) fireEvent.changeText(view.getByPlaceholderText(TITLE_PLACEHOLDER), title)
fireEvent.changeText(view.getByPlaceholderText(MESSAGE_PLACEHOLDER), message) fireEvent.changeText(view.getByPlaceholderText(MESSAGE_PLACEHOLDER), message)
} }
async function pressSendButton(view: ReturnType<typeof renderPage>) { async function pressSendButton(view: View) {
fireEvent.press(view.getByTestId('send-notification-button')) fireEvent.press(view.getByTestId('send-notification-button'))
await flush(2) await flush(2)
} }
async function openDropdown(view: View) {
fireEvent.press(view.getByTestId('notification-user-dropdown'))
await flush()
}
async function pressAlertButton(label: 'Cancel' | 'Send') { async function pressAlertButton(label: 'Cancel' | 'Send') {
const call = alertSpy.mock.calls.filter((args) => Array.isArray(args[2])).pop() const call = alertSpy.mock.calls.filter((args) => Array.isArray(args[2])).pop()
const button = (call?.[2] ?? []).find((item: any) => item.text === label) const button = (call?.[2] ?? []).find((item: any) => item.text === label)
@ -63,16 +72,16 @@ describe('Send notifications (ANOTIF-01..16)', () => {
await flush(2) await flush(2)
} }
it('ANOTIF-01: shows the loading state while eligible users load', () => { it('ANOTIF-01: shows the loading state while eligible users load', async () => {
setProcedure('admin.user.getUsersForNotification', { mode: 'pending' }) setProcedure('admin.user.getUsersForNotification', { mode: 'pending' })
const view = renderPage() const view = await renderPage()
expect(view.getByText('Loading users...')).toBeTruthy() expect(view.getByText('Loading users...')).toBeTruthy()
}) })
it('ANOTIF-02: renders the title, message, user dropdown and send button', () => { it('ANOTIF-02: renders the title, message, user dropdown and send button', async () => {
const view = renderPage() const view = await renderPage()
expect(view.getByText('Send Notifications')).toBeTruthy() expect(view.getByText('Send Notifications')).toBeTruthy()
expect(view.getByText('Title')).toBeTruthy() expect(view.getByText('Title')).toBeTruthy()
@ -87,7 +96,7 @@ describe('Send notifications (ANOTIF-01..16)', () => {
}) })
it('ANOTIF-03: an empty title alerts "Please enter a title"', async () => { it('ANOTIF-03: an empty title alerts "Please enter a title"', async () => {
const view = renderPage() const view = await renderPage()
// The button is disabled until both fields are filled, so invoke the // The button is disabled until both fields are filled, so invoke the
// handler the touchable would run (the validation branch is UI-reachable // handler the touchable would run (the validation branch is UI-reachable
@ -105,7 +114,7 @@ describe('Send notifications (ANOTIF-01..16)', () => {
}) })
it('ANOTIF-04: an empty message alerts "Please enter a message"', async () => { it('ANOTIF-04: an empty message alerts "Please enter a message"', async () => {
const view = renderPage() const view = await renderPage()
fireEvent.changeText(view.getByPlaceholderText(TITLE_PLACEHOLDER), 'Hello') fireEvent.changeText(view.getByPlaceholderText(TITLE_PLACEHOLDER), 'Hello')
const button = view const button = view
@ -121,21 +130,19 @@ describe('Send notifications (ANOTIF-01..16)', () => {
}) })
it('ANOTIF-05: no eligible users leaves the dropdown empty but still allows send-to-all', async () => { it('ANOTIF-05: no eligible users leaves the dropdown empty but still allows send-to-all', async () => {
const view = renderPage() const view = await renderPage()
await flush()
expect(view.getByText('Send to All Users')).toBeTruthy() expect(view.getByText('Send to All Users')).toBeTruthy()
expect(view.getByText('All Users')).toBeTruthy() expect(view.getByText('All Users')).toBeTruthy()
fireEvent.press(view.getByTestId('notification-user-dropdown')) await openDropdown(view)
await flush()
expect(view.queryByTestId('notification-user-dropdown-option-5')).toBeNull() expect(view.queryByTestId('notification-user-dropdown-option-5')).toBeNull()
expect(view.queryByTestId('notification-user-dropdown-option-6')).toBeNull() expect(view.queryByTestId('notification-user-dropdown-option-6')).toBeNull()
}) })
it('ANOTIF-06: Send to All asks for confirmation and Cancel sends nothing', async () => { it('ANOTIF-06: Send to All asks for confirmation and Cancel sends nothing', async () => {
const view = renderPage() const view = await renderPage()
fillForm(view) fillForm(view)
await pressSendButton(view) await pressSendButton(view)
@ -154,26 +161,26 @@ describe('Send notifications (ANOTIF-01..16)', () => {
}) })
it('ANOTIF-07: confirming all sends an empty userIds payload with trimmed title/text', async () => { it('ANOTIF-07: confirming all sends an empty userIds payload with trimmed title/text', async () => {
const view = renderPage() const view = await renderPage()
fillForm(view, ' Hello ', ' World ') fillForm(view, ' Hello ', ' World ')
await pressSendButton(view) await pressSendButton(view)
await pressAlertButton('Send') await pressAlertButton('Send')
await waitFor(() =>
expect(lastMutationInput('admin.user.sendNotification')).toEqual({ expect(lastMutationInput('admin.user.sendNotification')).toEqual({
userIds: [], userIds: [],
title: 'Hello', title: 'Hello',
text: 'World', text: 'World',
}) })
)
}) })
it('ANOTIF-08: selected users are sent as their ids', async () => { it('ANOTIF-08: selected users are sent as their ids', async () => {
setEligibleUsers() setEligibleUsers()
const view = renderPage() const view = await renderPage()
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown')) await openDropdown(view)
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown-option-5')) fireEvent.press(view.getByTestId('notification-user-dropdown-option-5'))
fireEvent.press(view.getByTestId('notification-user-dropdown-option-6')) fireEvent.press(view.getByTestId('notification-user-dropdown-option-6'))
fireEvent.press(view.getByTestId('notification-user-dropdown-done')) fireEvent.press(view.getByTestId('notification-user-dropdown-done'))
@ -182,20 +189,20 @@ describe('Send notifications (ANOTIF-01..16)', () => {
fillForm(view) fillForm(view)
await pressSendButton(view) await pressSendButton(view)
await waitFor(() =>
expect(lastMutationInput('admin.user.sendNotification')).toEqual({ expect(lastMutationInput('admin.user.sendNotification')).toEqual({
userIds: [5, 6], userIds: [5, 6],
title: 'Hello', title: 'Hello',
text: 'World', text: 'World',
}) })
)
}) })
it('ANOTIF-09: one selected user is displayed as mobile - name', async () => { it('ANOTIF-09: one selected user is displayed as mobile - name', async () => {
setEligibleUsers() setEligibleUsers()
const view = renderPage() const view = await renderPage()
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown')) await openDropdown(view)
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown-option-5')) fireEvent.press(view.getByTestId('notification-user-dropdown-option-5'))
fireEvent.press(view.getByTestId('notification-user-dropdown-done')) fireEvent.press(view.getByTestId('notification-user-dropdown-done'))
await flush() await flush()
@ -206,11 +213,9 @@ describe('Send notifications (ANOTIF-01..16)', () => {
it('ANOTIF-10: multiple selections display "N users selected"', async () => { it('ANOTIF-10: multiple selections display "N users selected"', async () => {
setEligibleUsers() setEligibleUsers()
const view = renderPage() const view = await renderPage()
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown')) await openDropdown(view)
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown-option-5')) fireEvent.press(view.getByTestId('notification-user-dropdown-option-5'))
fireEvent.press(view.getByTestId('notification-user-dropdown-option-6')) fireEvent.press(view.getByTestId('notification-user-dropdown-option-6'))
fireEvent.press(view.getByTestId('notification-user-dropdown-done')) fireEvent.press(view.getByTestId('notification-user-dropdown-done'))
@ -221,31 +226,30 @@ describe('Send notifications (ANOTIF-01..16)', () => {
it('ANOTIF-11: searching the dropdown refetches users with the query', async () => { it('ANOTIF-11: searching the dropdown refetches users with the query', async () => {
setEligibleUsers() setEligibleUsers()
const view = renderPage() const view = await renderPage()
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown')) await openDropdown(view)
await flush()
jest.useFakeTimers()
fireEvent.changeText(view.getByTestId('notification-user-dropdown-search'), '987') fireEvent.changeText(view.getByTestId('notification-user-dropdown-search'), '987')
await act(async () => {
await jest.advanceTimersByTimeAsync(2100)
})
const searches = procedureQueryCalls('admin.user.getUsersForNotification').map((input) => input?.search) // The dropdown debounces `onSearch` by 2s; wait for the refetch it triggers.
await waitFor(
() => {
const searches = procedureQueryCalls('admin.user.getUsersForNotification').map(
(input) => input?.search
)
expect(searches).toContain('987') expect(searches).toContain('987')
jest.useRealTimers() },
{ timeout: 4000 }
)
}) })
it('ANOTIF-12: a pending send shows "Sending..." and blocks a second submit', async () => { it('ANOTIF-12: a pending send shows "Sending..." and blocks a second submit', async () => {
setEligibleUsers() setEligibleUsers()
setProcedure('admin.user.sendNotification', { mode: 'pending' }) setProcedure('admin.user.sendNotification', { mode: 'pending' })
const view = renderPage() const view = await renderPage()
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown')) await openDropdown(view)
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown-option-5')) fireEvent.press(view.getByTestId('notification-user-dropdown-option-5'))
fireEvent.press(view.getByTestId('notification-user-dropdown-done')) fireEvent.press(view.getByTestId('notification-user-dropdown-done'))
await flush() await flush()
@ -262,13 +266,15 @@ describe('Send notifications (ANOTIF-01..16)', () => {
}) })
it('ANOTIF-13: success alerts and resets the form and selection', async () => { it('ANOTIF-13: success alerts and resets the form and selection', async () => {
const view = renderPage() const view = await renderPage()
fillForm(view, 'Hello', 'World') fillForm(view, 'Hello', 'World')
await pressSendButton(view) await pressSendButton(view)
await pressAlertButton('Send') await pressAlertButton('Send')
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Notification sent successfully!') expect(alertSpy).toHaveBeenCalledWith('Success', 'Notification sent successfully!')
)
expect(view.getByPlaceholderText(TITLE_PLACEHOLDER).props.value).toBe('') expect(view.getByPlaceholderText(TITLE_PLACEHOLDER).props.value).toBe('')
expect(view.getByPlaceholderText(MESSAGE_PLACEHOLDER).props.value).toBe('') expect(view.getByPlaceholderText(MESSAGE_PLACEHOLDER).props.value).toBe('')
expect(view.getByText('All Users')).toBeTruthy() expect(view.getByText('All Users')).toBeTruthy()
@ -277,11 +283,9 @@ describe('Send notifications (ANOTIF-01..16)', () => {
it('ANOTIF-14: a failed send alerts the mutation error', async () => { it('ANOTIF-14: a failed send alerts the mutation error', async () => {
setEligibleUsers() setEligibleUsers()
setProcedure('admin.user.sendNotification', { mode: 'error', error: new Error('send failed') }) setProcedure('admin.user.sendNotification', { mode: 'error', error: new Error('send failed') })
const view = renderPage() const view = await renderPage()
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown')) await openDropdown(view)
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown-option-5')) fireEvent.press(view.getByTestId('notification-user-dropdown-option-5'))
fireEvent.press(view.getByTestId('notification-user-dropdown-done')) fireEvent.press(view.getByTestId('notification-user-dropdown-done'))
await flush() await flush()
@ -289,17 +293,15 @@ describe('Send notifications (ANOTIF-01..16)', () => {
fillForm(view) fillForm(view)
await pressSendButton(view) await pressSendButton(view)
expect(alertSpy).toHaveBeenCalledWith('Error', 'send failed') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'send failed'))
}) })
it('ANOTIF-15: a failed send alerts twice (mutation onError + catch) — current gap', async () => { it('ANOTIF-15: a failed send alerts twice (mutation onError + catch) — current gap', async () => {
setEligibleUsers() setEligibleUsers()
setProcedure('admin.user.sendNotification', { mode: 'error', error: new Error('send failed') }) setProcedure('admin.user.sendNotification', { mode: 'error', error: new Error('send failed') })
const view = renderPage() const view = await renderPage()
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown')) await openDropdown(view)
await flush()
fireEvent.press(view.getByTestId('notification-user-dropdown-option-5')) fireEvent.press(view.getByTestId('notification-user-dropdown-option-5'))
fireEvent.press(view.getByTestId('notification-user-dropdown-done')) fireEvent.press(view.getByTestId('notification-user-dropdown-done'))
await flush() await flush()
@ -307,14 +309,16 @@ describe('Send notifications (ANOTIF-01..16)', () => {
fillForm(view) fillForm(view)
await pressSendButton(view) await pressSendButton(view)
await waitFor(() => {
const errorAlerts = alertSpy.mock.calls.filter( const errorAlerts = alertSpy.mock.calls.filter(
(args) => args[0] === 'Error' && args[1] === 'send failed' (args) => args[0] === 'Error' && args[1] === 'send failed'
) )
expect(errorAlerts).toHaveLength(2) expect(errorAlerts).toHaveLength(2)
}) })
})
it('ANOTIF-16: the back button calls router.back', () => { it('ANOTIF-16: the back button calls router.back', async () => {
const view = renderPage() const view = await renderPage()
fireEvent.press(view.getByTestId('send-notifications-back')) fireEvent.press(view.getByTestId('send-notifications-back'))

View file

@ -4,10 +4,10 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import AddSlot from '@/app/(drawer)/dashboard/slots/add' import AddSlot from '@/app/(drawer)/dashboard/slots/add'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -20,11 +20,11 @@ import { __setParams, router } from '../mocks/expo-router-mock'
const HOUR = 60 * 60 * 1000 const HOUR = 60 * 60 * 1000
function renderAddSlot() { function renderAddSlot() {
return renderWithProviders(<AddSlot />, { auth: 'in' }) return renderAndFlush(<AddSlot />, { auth: 'in' })
} }
function chooseDate( function chooseDate(
view: ReturnType<typeof renderAddSlot>, view: Awaited<ReturnType<typeof renderAddSlot>>,
field: 'delivery' | 'freeze', field: 'delivery' | 'freeze',
date: Date date: Date
) { ) {
@ -43,8 +43,8 @@ describe('Add slot (ASLOTADD-01..06)', () => {
afterEach(() => alertSpy?.mockRestore()) afterEach(() => alertSpy?.mockRestore())
it('ASLOTADD-01: with no base slot the form is blank', () => { it('ASLOTADD-01: with no base slot the form is blank', async () => {
const view = renderAddSlot() const view = await renderAddSlot()
expect(view.getByText('Create New Slot')).toBeTruthy() expect(view.getByText('Create New Slot')).toBeTruthy()
expect(view.getByText('Select products for this slot')).toBeTruthy() expect(view.getByText('Select products for this slot')).toBeTruthy()
@ -56,14 +56,15 @@ describe('Add slot (ASLOTADD-01..06)', () => {
it('ASLOTADD-02: a base slot shows the loading copy', () => { it('ASLOTADD-02: a base slot shows the loading copy', () => {
__setParams({ baseslot: '1849' }) __setParams({ baseslot: '1849' })
setProcedure('admin.slots.getSlotById', { mode: 'pending' }) setProcedure('admin.slots.getSlotById', { mode: 'pending' })
const view = renderAddSlot() const view = renderWithProviders(<AddSlot />, { auth: 'in' })
// Loading assertions stay synchronous: the query never settles.
expect(view.getByText('Loading base slot...')).toBeTruthy() expect(view.getByText('Loading base slot...')).toBeTruthy()
}) })
it('ASLOTADD-03: loads the base slot and seeds the form from it', () => { it('ASLOTADD-03: loads the base slot and seeds the form from it', async () => {
__setParams({ baseslot: '1849' }) __setParams({ baseslot: '1849' })
const view = renderAddSlot() const view = await renderAddSlot()
expect(procedureQueryCalls('admin.slots.getSlotById')).toContainEqual({ id: 1849 }) expect(procedureQueryCalls('admin.slots.getSlotById')).toContainEqual({ id: 1849 })
expect(view.getByText('Create New Slot')).toBeTruthy() expect(view.getByText('Create New Slot')).toBeTruthy()
@ -73,25 +74,25 @@ describe('Add slot (ASLOTADD-01..06)', () => {
expect(view.getAllByText('Select Date').length).toBeGreaterThanOrEqual(2) expect(view.getAllByText('Select Date').length).toBeGreaterThanOrEqual(2)
}) })
it('ASLOTADD-04: a missing base slot falls back to a blank form', () => { it('ASLOTADD-04: a missing base slot falls back to a blank form', async () => {
__setParams({ baseslot: '9999' }) __setParams({ baseslot: '9999' })
setProcedure('admin.slots.getSlotById', { data: {} }) setProcedure('admin.slots.getSlotById', { data: {} })
const view = renderAddSlot() const view = await renderAddSlot()
expect(view.queryByText('Loading base slot...')).toBeNull() expect(view.queryByText('Loading base slot...')).toBeNull()
expect(view.getByText('Create New Slot')).toBeTruthy() expect(view.getByText('Create New Slot')).toBeTruthy()
}) })
it('ASLOTADD-05: creating a slot sends the payload and goes back', async () => { it('ASLOTADD-05: creating a slot sends the payload and goes back', async () => {
const view = renderAddSlot() const view = await renderAddSlot()
const delivery = new Date(Date.now() + 3 * HOUR) const delivery = new Date(Date.now() + 3 * HOUR)
const freeze = new Date(Date.now() + 2 * HOUR) const freeze = new Date(Date.now() + 2 * HOUR)
chooseDate(view, 'delivery', delivery) chooseDate(view, 'delivery', delivery)
chooseDate(view, 'freeze', freeze) chooseDate(view, 'freeze', freeze)
fireEvent.press(view.getByTestId('create-slot-button')) fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.slots.createSlot')).toEqual({ expect(lastMutationInput('admin.slots.createSlot')).toEqual({
deliveryTime: delivery.toISOString(), deliveryTime: delivery.toISOString(),
freezeTime: freeze.toISOString(), freezeTime: freeze.toISOString(),
@ -100,23 +101,25 @@ describe('Add slot (ASLOTADD-01..06)', () => {
skuIds: [], skuIds: [],
vendorSnippets: [], vendorSnippets: [],
}) })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot created successfully!') expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot created successfully!')
expect(router.back).toHaveBeenCalled() )
await waitFor(() => expect(router.back).toHaveBeenCalled())
}) })
it('ASLOTADD-06: a create failure alerts and stays on the form', async () => { it('ASLOTADD-06: a create failure alerts and stays on the form', async () => {
setProcedure('admin.slots.createSlot', { mode: 'error', error: new Error('boom') }) setProcedure('admin.slots.createSlot', { mode: 'error', error: new Error('boom') })
const view = renderAddSlot() const view = await renderAddSlot()
const delivery = new Date(Date.now() + 3 * HOUR) const delivery = new Date(Date.now() + 3 * HOUR)
const freeze = new Date(Date.now() + 2 * HOUR) const freeze = new Date(Date.now() + 2 * HOUR)
chooseDate(view, 'delivery', delivery) chooseDate(view, 'delivery', delivery)
chooseDate(view, 'freeze', freeze) chooseDate(view, 'freeze', freeze)
fireEvent.press(view.getByTestId('create-slot-button')) fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'boom'))
expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(1) expect(procedureMutationCalls('admin.slots.createSlot')).toHaveLength(1)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
expect(router.back).not.toHaveBeenCalled() expect(router.back).not.toHaveBeenCalled()
}) })
}) })

View file

@ -4,18 +4,18 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, Share } from 'react-native' import { Alert, Share } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import SlotDetails from '@/app/(drawer)/dashboard/slots/slot-details' import SlotDetails from '@/app/(drawer)/dashboard/slots/slot-details'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client' import { setProcedure } from '../mocks/trpc-client'
import { __setParams, router } from '../mocks/expo-router-mock' import { __setParams, router } from '../mocks/expo-router-mock'
import { SLOT_DETAIL } from '../fixtures' import { SLOT_DETAIL } from '../fixtures'
function renderDetails() { function renderDetails() {
return renderWithProviders(<SlotDetails />, { auth: 'in' }) return renderAndFlush(<SlotDetails />, { auth: 'in' })
} }
const SNIPPET = SLOT_DETAIL.vendorSnippets[0] const SNIPPET = SLOT_DETAIL.vendorSnippets[0]
@ -37,30 +37,31 @@ describe('Slot details (ASLOTDET-01..10)', () => {
it('ASLOTDET-01: shows the loading copy', () => { it('ASLOTDET-01: shows the loading copy', () => {
setProcedure('admin.slots.getSlotById', { mode: 'pending' }) setProcedure('admin.slots.getSlotById', { mode: 'pending' })
const view = renderDetails() const view = renderWithProviders(<SlotDetails />, { auth: 'in' })
// Loading assertions stay synchronous: the query never settles.
expect(view.getByText('Loading slot details...')).toBeTruthy() expect(view.getByText('Loading slot details...')).toBeTruthy()
}) })
it('ASLOTDET-02: a query error shows the error copy', () => { it('ASLOTDET-02: a query error shows the error copy', async () => {
setProcedure('admin.slots.getSlotById', { mode: 'error', error: new Error('boom') }) setProcedure('admin.slots.getSlotById', { mode: 'error', error: new Error('boom') })
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('Error loading slot details')).toBeTruthy() expect(await view.findByText('Error loading slot details')).toBeTruthy()
}) })
it('ASLOTDET-03: with no vendor snippets the empty copy is shown', () => { it('ASLOTDET-03: with no vendor snippets the empty copy is shown', async () => {
setProcedure('admin.slots.getSlotById', { setProcedure('admin.slots.getSlotById', {
data: { slot: { ...SLOT_DETAIL, vendorSnippets: [] } }, data: { slot: { ...SLOT_DETAIL, vendorSnippets: [] } },
}) })
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('No vendor snippets for this slot')).toBeTruthy() expect(view.getByText('No vendor snippets for this slot')).toBeTruthy()
expect(view.getByText('0 snippets')).toBeTruthy() expect(view.getByText('0 snippets')).toBeTruthy()
}) })
it('ASLOTDET-04: renders snippet code, expiry and share action', () => { it('ASLOTDET-04: renders snippet code, expiry and share action', async () => {
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('ABC123')).toBeTruthy() expect(view.getByText('ABC123')).toBeTruthy()
expect(view.getByText('1 snippets')).toBeTruthy() expect(view.getByText('1 snippets')).toBeTruthy()
@ -68,8 +69,8 @@ describe('Slot details (ASLOTDET-01..10)', () => {
expect(view.getByText(`Expires ${dayjs(SNIPPET.validTill).format('MMM DD')}`)).toBeTruthy() expect(view.getByText(`Expires ${dayjs(SNIPPET.validTill).format('MMM DD')}`)).toBeTruthy()
}) })
it('ASLOTDET-05: renders product names/count and the empty copy', () => { it('ASLOTDET-05: renders product names/count and the empty copy', async () => {
const view = renderDetails() const view = await renderDetails()
expect(view.getByText('2 items')).toBeTruthy() expect(view.getByText('2 items')).toBeTruthy()
expect(view.getByText('Chicken Breast')).toBeTruthy() expect(view.getByText('Chicken Breast')).toBeTruthy()
expect(view.getByText('Cucumber')).toBeTruthy() expect(view.getByText('Cucumber')).toBeTruthy()
@ -78,13 +79,13 @@ describe('Slot details (ASLOTDET-01..10)', () => {
setProcedure('admin.slots.getSlotById', { setProcedure('admin.slots.getSlotById', {
data: { slot: { ...SLOT_DETAIL, products: [], vendorSnippets: [] } }, data: { slot: { ...SLOT_DETAIL, products: [], vendorSnippets: [] } },
}) })
const empty = renderDetails() const empty = await renderDetails()
expect(empty.getByText('0 items')).toBeTruthy() expect(empty.getByText('0 items')).toBeTruthy()
expect(empty.getByText('No products in this slot')).toBeTruthy() expect(empty.getByText('No products in this slot')).toBeTruthy()
}) })
it('ASLOTDET-06: the edit FAB opens the edit route', () => { it('ASLOTDET-06: the edit FAB opens the edit route', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByTestId('edit-slot-fab')) fireEvent.press(view.getByTestId('edit-slot-fab'))
@ -93,21 +94,19 @@ describe('Slot details (ASLOTDET-01..10)', () => {
it('ASLOTDET-07: a failed share alerts', async () => { it('ASLOTDET-07: a failed share alerts', async () => {
;(Share.share as jest.Mock).mockRejectedValue(new Error('share failed')) ;(Share.share as jest.Mock).mockRejectedValue(new Error('share failed'))
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByText('Share')) fireEvent.press(view.getByText('Share'))
await flush(2)
expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to share link') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'Failed to share link'))
}) })
it('ASLOTDET-08: a successful share passes the access URL', async () => { it('ASLOTDET-08: a successful share passes the access URL', async () => {
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByText('Share')) fireEvent.press(view.getByText('Share'))
await flush(2)
expect(Share.share).toHaveBeenCalledWith({ message: SNIPPET.accessUrl }) await waitFor(() => expect(Share.share).toHaveBeenCalledWith({ message: SNIPPET.accessUrl }))
}) })
it('ASLOTDET-09: a snippet without a link shares an undefined message', async () => { it('ASLOTDET-09: a snippet without a link shares an undefined message', async () => {
@ -119,15 +118,14 @@ describe('Slot details (ASLOTDET-01..10)', () => {
}, },
}, },
}) })
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByText('Share')) fireEvent.press(view.getByText('Share'))
await flush(2)
expect(Share.share).toHaveBeenCalledWith({ message: undefined }) await waitFor(() => expect(Share.share).toHaveBeenCalledWith({ message: undefined }))
}) })
it('ASLOTDET-10: the snippet products dialog lists the matching products', () => { it('ASLOTDET-10: the snippet products dialog lists the matching products', async () => {
setProcedure('admin.slots.getSlotById', { setProcedure('admin.slots.getSlotById', {
data: { data: {
slot: { slot: {
@ -136,7 +134,7 @@ describe('Slot details (ASLOTDET-01..10)', () => {
}, },
}, },
}) })
const view = renderDetails() const view = await renderDetails()
fireEvent.press(view.getByText('2 products')) fireEvent.press(view.getByText('2 products'))

View file

@ -4,17 +4,17 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import EditSlot from '@/app/(drawer)/dashboard/slots/edit/[id]' import EditSlot from '@/app/(drawer)/dashboard/slots/edit/[id]'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client' import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
import { __setParams, router } from '../mocks/expo-router-mock' import { __setParams, router } from '../mocks/expo-router-mock'
import { SLOT_DETAIL } from '../fixtures' import { SLOT_DETAIL } from '../fixtures'
function renderEditSlot() { function renderEditSlot() {
return renderWithProviders(<EditSlot />, { auth: 'in' }) return renderAndFlush(<EditSlot />, { auth: 'in' })
} }
describe('Edit slot (ASLOTEDIT-01..05)', () => { describe('Edit slot (ASLOTEDIT-01..05)', () => {
@ -30,20 +30,21 @@ describe('Edit slot (ASLOTEDIT-01..05)', () => {
it('ASLOTEDIT-01: shows the loading copy', () => { it('ASLOTEDIT-01: shows the loading copy', () => {
setProcedure('admin.slots.getSlotById', { mode: 'pending' }) setProcedure('admin.slots.getSlotById', { mode: 'pending' })
const view = renderEditSlot() const view = renderWithProviders(<EditSlot />, { auth: 'in' })
// Loading assertions stay synchronous: the query never settles.
expect(view.getByText('Loading slot...')).toBeTruthy() expect(view.getByText('Loading slot...')).toBeTruthy()
}) })
it('ASLOTEDIT-02: a missing slot shows "Slot not found"', () => { it('ASLOTEDIT-02: a missing slot shows "Slot not found"', async () => {
setProcedure('admin.slots.getSlotById', { data: undefined }) setProcedure('admin.slots.getSlotById', { data: undefined })
const view = renderEditSlot() const view = await renderEditSlot()
expect(view.getByText('Slot not found')).toBeTruthy() expect(view.getByText('Slot not found')).toBeTruthy()
}) })
it('ASLOTEDIT-03: prefills times, active state, products, snippets and groups', () => { it('ASLOTEDIT-03: prefills times, active state, products, snippets and groups', async () => {
const view = renderEditSlot() const view = await renderEditSlot()
expect(view.getByText('Edit Slot')).toBeTruthy() expect(view.getByText('Edit Slot')).toBeTruthy()
expect( expect(
@ -53,18 +54,18 @@ describe('Edit slot (ASLOTEDIT-01..05)', () => {
view.getAllByText(new Date(SLOT_DETAIL.freezeTime).toLocaleDateString()).length view.getAllByText(new Date(SLOT_DETAIL.freezeTime).toLocaleDateString()).length
).toBeGreaterThanOrEqual(1) ).toBeGreaterThanOrEqual(1)
// The group selection is restored from the server payload. // The group selection is restored from the server payload.
expect(view.getByText('Breakfast')).toBeTruthy() expect(await view.findByText('Breakfast')).toBeTruthy()
// One snippet row is present for the slot's vendor snippet. // One snippet row is present for the slot's vendor snippet.
expect(view.getByText('Snippet Name *')).toBeTruthy() expect(view.getByText('Snippet Name *')).toBeTruthy()
expect(view.getByText('Update Slot')).toBeTruthy() expect(view.getByText('Update Slot')).toBeTruthy()
}) })
it('ASLOTEDIT-04: updating sends updateSlot with the restored values', async () => { it('ASLOTEDIT-04: updating sends updateSlot with the restored values', async () => {
const view = renderEditSlot() const view = await renderEditSlot()
fireEvent.press(view.getByTestId('create-slot-button')) fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
await waitFor(() =>
expect(lastMutationInput('admin.slots.updateSlot')).toEqual({ expect(lastMutationInput('admin.slots.updateSlot')).toEqual({
id: 1849, id: 1849,
deliveryTime: new Date(SLOT_DETAIL.deliveryTime).toISOString(), deliveryTime: new Date(SLOT_DETAIL.deliveryTime).toISOString(),
@ -80,19 +81,21 @@ describe('Edit slot (ASLOTEDIT-01..05)', () => {
}, },
], ],
}) })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot updated successfully!') expect(alertSpy).toHaveBeenCalledWith('Success', 'Slot updated successfully!')
expect(router.back).toHaveBeenCalled() )
await waitFor(() => expect(router.back).toHaveBeenCalled())
}) })
it('ASLOTEDIT-05: an update failure alerts and stays on the form', async () => { it('ASLOTEDIT-05: an update failure alerts and stays on the form', async () => {
setProcedure('admin.slots.updateSlot', { mode: 'error', error: new Error('boom') }) setProcedure('admin.slots.updateSlot', { mode: 'error', error: new Error('boom') })
const view = renderEditSlot() const view = await renderEditSlot()
fireEvent.press(view.getByTestId('create-slot-button')) fireEvent.press(view.getByTestId('create-slot-button'))
await flush(2)
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'boom'))
expect(procedureMutationCalls('admin.slots.updateSlot')).toHaveLength(1) expect(procedureMutationCalls('admin.slots.updateSlot')).toHaveLength(1)
expect(alertSpy).toHaveBeenCalledWith('Error', 'boom')
expect(router.back).not.toHaveBeenCalled() expect(router.back).not.toHaveBeenCalled()
}) })
}) })

View file

@ -4,21 +4,18 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import Slots from '@/app/(drawer)/dashboard/slots/index' import Slots from '@/app/(drawer)/dashboard/slots/index'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderWithProviders, renderAndFlush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client' import { setProcedure, lastMutationInput } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { SLOT_1 } from '../fixtures' import { SLOT_1 } from '../fixtures'
const HOUR = 60 * 60 * 1000
const iso = (offset: number) => new Date(Date.now() + offset).toISOString()
function renderSlots() { function renderSlots() {
return renderWithProviders(<Slots />, { auth: 'in' }) return renderAndFlush(<Slots />, { auth: 'in' })
} }
describe('Slot list (ASLOTUI-01..16)', () => { describe('Slot list (ASLOTUI-01..16)', () => {
@ -33,21 +30,22 @@ describe('Slot list (ASLOTUI-01..16)', () => {
it('ASLOTUI-01: shows the loading copy', () => { it('ASLOTUI-01: shows the loading copy', () => {
setProcedure('admin.slots.getAll', { mode: 'pending' }) setProcedure('admin.slots.getAll', { mode: 'pending' })
const view = renderSlots() const view = renderWithProviders(<Slots />, { auth: 'in' })
// Loading assertions stay synchronous: the query never settles.
expect(view.getByText('Loading slots...')).toBeTruthy() expect(view.getByText('Loading slots...')).toBeTruthy()
}) })
it('ASLOTUI-02: an empty response renders no slot rows', () => { it('ASLOTUI-02: an empty response renders no slot rows', async () => {
setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } }) setProcedure('admin.slots.getAll', { data: { slots: [], count: 0 } })
const view = renderSlots() const view = await renderSlots()
expect(view.queryByText(/^Slot #/)).toBeNull() expect(view.queryByText(/^Slot #/)).toBeNull()
expect(view.getByTestId('add-slot-fab')).toBeTruthy() expect(view.getByTestId('add-slot-fab')).toBeTruthy()
}) })
it('ASLOTUI-03: renders slot id, delivery/freeze times, status and products', () => { it('ASLOTUI-03: renders slot id, delivery/freeze times, status and products', async () => {
const view = renderSlots() const view = await renderSlots()
expect(view.getByText('Slot #1849')).toBeTruthy() expect(view.getByText('Slot #1849')).toBeTruthy()
expect(view.getByText('ID: 1849')).toBeTruthy() expect(view.getByText('ID: 1849')).toBeTruthy()
@ -57,19 +55,19 @@ describe('Slot list (ASLOTUI-01..16)', () => {
expect(view.getAllByText('Active').length).toBeGreaterThanOrEqual(1) expect(view.getAllByText('Active').length).toBeGreaterThanOrEqual(1)
}) })
it('ASLOTUI-04: an inactive slot shows the Inactive status', () => { it('ASLOTUI-04: an inactive slot shows the Inactive status', async () => {
const view = renderSlots() const view = await renderSlots()
expect(view.getByText('Inactive')).toBeTruthy() expect(view.getByText('Inactive')).toBeTruthy()
}) })
it('ASLOTUI-05: a full-capacity slot shows the FULL badge', () => { it('ASLOTUI-05: a full-capacity slot shows the FULL badge', async () => {
const view = renderSlots() const view = await renderSlots()
expect(view.getByText('FULL')).toBeTruthy() expect(view.getByText('FULL')).toBeTruthy()
}) })
it('ASLOTUI-06: more than two products shows "+N more" and opens the dialog', () => { it('ASLOTUI-06: more than two products shows "+N more" and opens the dialog', async () => {
setProcedure('admin.slots.getAll', { setProcedure('admin.slots.getAll', {
data: { data: {
slots: [ slots: [
@ -86,15 +84,15 @@ describe('Slot list (ASLOTUI-01..16)', () => {
count: 1, count: 1,
}, },
}) })
const view = renderSlots() const view = await renderSlots()
expect(view.getByText('+2 more')).toBeTruthy() expect(view.getByText('+2 more')).toBeTruthy()
fireEvent.press(view.getByText('+2 more')) fireEvent.press(view.getByText('+2 more'))
expect(view.getByText('All Products')).toBeTruthy() expect(view.getByText('All Products')).toBeTruthy()
}) })
it('ASLOTUI-07: tapping a slot card opens the details route', () => { it('ASLOTUI-07: tapping a slot card opens the details route', async () => {
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByText('Slot #1849')) fireEvent.press(view.getByText('Slot #1849'))
@ -103,16 +101,16 @@ describe('Slot list (ASLOTUI-01..16)', () => {
) )
}) })
it('ASLOTUI-08: the edit chip opens the edit route', () => { it('ASLOTUI-08: the edit chip opens the edit route', async () => {
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByTestId('edit-slot-1849')) fireEvent.press(view.getByTestId('edit-slot-1849'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/edit/1849') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/edit/1849')
}) })
it('ASLOTUI-09: the menu opens the actions dialog', () => { it('ASLOTUI-09: the menu opens the actions dialog', async () => {
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByTestId('slot-menu-1849')) fireEvent.press(view.getByTestId('slot-menu-1849'))
@ -122,37 +120,43 @@ describe('Slot list (ASLOTUI-01..16)', () => {
}) })
it('ASLOTUI-10: marking a slot full sends isCapacityFull true', async () => { it('ASLOTUI-10: marking a slot full sends isCapacityFull true', async () => {
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByTestId('slot-menu-1849')) fireEvent.press(view.getByTestId('slot-menu-1849'))
fireEvent.press(view.getByText('Mark as Full Capacity')) fireEvent.press(view.getByText('Mark as Full Capacity'))
await flush()
await waitFor(() =>
expect(lastMutationInput('admin.slots.updateSlotCapacity')).toEqual({ expect(lastMutationInput('admin.slots.updateSlotCapacity')).toEqual({
slotId: 1849, slotId: 1849,
isCapacityFull: true, isCapacityFull: true,
}) })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Success', 'Success',
'Slot marked as full capacity. It will be hidden from users.' 'Slot marked as full capacity. It will be hidden from users.'
) )
)
}) })
it('ASLOTUI-11: marking a full slot not-full sends isCapacityFull false', async () => { it('ASLOTUI-11: marking a full slot not-full sends isCapacityFull false', async () => {
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByTestId('slot-menu-1850')) fireEvent.press(view.getByTestId('slot-menu-1850'))
fireEvent.press(view.getByText('Mark as Full Capacity')) fireEvent.press(view.getByText('Mark as Full Capacity'))
await flush()
await waitFor(() =>
expect(lastMutationInput('admin.slots.updateSlotCapacity')).toEqual({ expect(lastMutationInput('admin.slots.updateSlotCapacity')).toEqual({
slotId: 1850, slotId: 1850,
isCapacityFull: false, isCapacityFull: false,
}) })
)
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith( expect(alertSpy).toHaveBeenCalledWith(
'Success', 'Success',
'Slot capacity reset. It will now be visible to users.' 'Slot capacity reset. It will now be visible to users.'
) )
)
}) })
it('ASLOTUI-12: a failed capacity update alerts the error', async () => { it('ASLOTUI-12: a failed capacity update alerts the error', async () => {
@ -160,17 +164,16 @@ describe('Slot list (ASLOTUI-01..16)', () => {
mode: 'error', mode: 'error',
error: new Error('nope'), error: new Error('nope'),
}) })
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByTestId('slot-menu-1849')) fireEvent.press(view.getByTestId('slot-menu-1849'))
fireEvent.press(view.getByText('Mark as Full Capacity')) fireEvent.press(view.getByText('Mark as Full Capacity'))
await flush()
expect(alertSpy).toHaveBeenCalledWith('Error', 'nope') await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'nope'))
}) })
it('ASLOTUI-13: replicate opens add with the base slot param', () => { it('ASLOTUI-13: replicate opens add with the base slot param', async () => {
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByTestId('slot-menu-1849')) fireEvent.press(view.getByTestId('slot-menu-1849'))
fireEvent.press(view.getByText('Replicate Slot')) fireEvent.press(view.getByText('Replicate Slot'))
@ -178,15 +181,15 @@ describe('Slot list (ASLOTUI-01..16)', () => {
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/add?baseslot=1849') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/add?baseslot=1849')
}) })
it('ASLOTUI-14: the FAB opens the add route', () => { it('ASLOTUI-14: the FAB opens the add route', async () => {
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByTestId('add-slot-fab')) fireEvent.press(view.getByTestId('add-slot-fab'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/add') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/slots/add')
}) })
it('ASLOTUI-15: the products dialog lists every product name', () => { it('ASLOTUI-15: the products dialog lists every product name', async () => {
setProcedure('admin.slots.getAll', { setProcedure('admin.slots.getAll', {
data: { data: {
slots: [ slots: [
@ -202,7 +205,7 @@ describe('Slot list (ASLOTUI-01..16)', () => {
count: 1, count: 1,
}, },
}) })
const view = renderSlots() const view = await renderSlots()
fireEvent.press(view.getByText('+1 more')) fireEvent.press(view.getByText('+1 more'))
@ -212,11 +215,11 @@ describe('Slot list (ASLOTUI-01..16)', () => {
expect(view.getByText('Paneer')).toBeTruthy() expect(view.getByText('Paneer')).toBeTruthy()
}) })
it('ASLOTUI-16: a slot without products renders no product row', () => { it('ASLOTUI-16: a slot without products renders no product row', async () => {
setProcedure('admin.slots.getAll', { setProcedure('admin.slots.getAll', {
data: { slots: [{ ...SLOT_1, products: [] }], count: 1 }, data: { slots: [{ ...SLOT_1, products: [] }], count: 1 },
}) })
const view = renderSlots() const view = await renderSlots()
expect(view.getByText('Slot #1849')).toBeTruthy() expect(view.getByText('Slot #1849')).toBeTruthy()
expect(view.queryByText('Products')).toBeNull() expect(view.queryByText('Products')).toBeNull()

View file

@ -4,7 +4,7 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
import AddStore from '@/app/(drawer)/dashboard/stores/add' import AddStore from '@/app/(drawer)/dashboard/stores/add'
@ -12,6 +12,7 @@ import { renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
setRawFetchHandler,
lastMutationInput, lastMutationInput,
procedureMutationCalls, procedureMutationCalls,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
@ -63,11 +64,12 @@ describe('Add store (ASTOREADD-01..07)', () => {
resetAllMocks() resetAllMocks()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({ canceled: true, assets: null }) ;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({ canceled: true, assets: null })
;(global as any).fetch = jest.fn(async (url: string) => { // Non-tRPC requests (file:// reads and presigned PUTs) go through the raw handler.
setRawFetchHandler(async (url: string) => {
if (String(url).startsWith('file:')) { if (String(url).startsWith('file:')) {
return { ok: true, blob: async () => ({ size: 1 }) } return { ok: true, blob: async () => ({ size: 1 }) } as any
} }
return { ok: true, status: 200, text: async () => '' } return { ok: true, status: 200, text: async () => '' } as any
}) })
}) })
@ -156,8 +158,14 @@ describe('Add store (ASTOREADD-01..07)', () => {
await submitNewStore(view, 'No Image Store') await submitNewStore(view, 'No Image Store')
expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(0) expect(procedureMutationCalls('common.generateUploadUrls')).toHaveLength(0)
expect(lastMutationInput('admin.store.createStore')).toEqual( // `undefined` is dropped from the JSON body, so the store payload has no
expect.objectContaining({ imageUrl: undefined }) // imageUrl key at all — exactly the "no image" contract.
) const payload = lastMutationInput('admin.store.createStore')
expect(payload).toEqual({
name: 'No Image Store',
description: '',
products: [],
})
expect(payload).not.toHaveProperty('imageUrl')
}) })
}) })

View file

@ -4,13 +4,18 @@
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import * as ImagePicker from 'expo-image-picker' import * as ImagePicker from 'expo-image-picker'
import EditStore from '@/app/(drawer)/dashboard/stores/edit' import EditStore from '@/app/(drawer)/dashboard/stores/edit'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client' import {
setProcedure,
setRawFetchHandler,
lastMutationInput,
procedureMutationCalls,
} from '../mocks/trpc-client'
import { __setParams, router } from '../mocks/expo-router-mock' import { __setParams, router } from '../mocks/expo-router-mock'
import { STORE_1, STORE_GLOBAL } from '../fixtures' import { STORE_1, STORE_GLOBAL } from '../fixtures'
@ -42,8 +47,10 @@ const PICKED_IMAGE = {
assets: [{ uri: 'file:///tmp/store.jpg', mimeType: 'image/jpeg', fileName: 'store.jpg' }], assets: [{ uri: 'file:///tmp/store.jpg', mimeType: 'image/jpeg', fileName: 'store.jpg' }],
} }
function renderEdit() { async function renderEdit() {
return renderWithProviders(<EditStore />, { auth: 'in' }) const view = await renderAndFlush(<EditStore />, { auth: 'in' })
await flush(4)
return view
} }
const PRESELECTED = [11, 12, 13, 61, 71, 81, 82] const PRESELECTED = [11, 12, 13, 61, 71, 81, 82]
@ -56,11 +63,12 @@ describe('Edit store (ASTOREEDIT-01..12)', () => {
__setParams({ id: '1' }) __setParams({ id: '1' })
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({ canceled: true, assets: null }) ;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({ canceled: true, assets: null })
;(global as any).fetch = jest.fn(async (url: string) => { // Non-tRPC requests (file:// reads and presigned PUTs) go through the raw handler.
setRawFetchHandler(async (url: string) => {
if (String(url).startsWith('file:')) { if (String(url).startsWith('file:')) {
return { ok: true, blob: async () => ({ size: 1 }) } return { ok: true, blob: async () => ({ size: 1 }) } as any
} }
return { ok: true, status: 200, text: async () => '' } return { ok: true, status: 200, text: async () => '' } as any
}) })
}) })
@ -68,20 +76,21 @@ describe('Edit store (ASTOREEDIT-01..12)', () => {
it('ASTOREEDIT-01: shows the loading copy', () => { it('ASTOREEDIT-01: shows the loading copy', () => {
setProcedure('admin.store.getStoreById', { mode: 'pending' }) setProcedure('admin.store.getStoreById', { mode: 'pending' })
const view = renderEdit() // Loading state is asserted synchronously, before the query settles.
const view = renderWithProviders(<EditStore />, { auth: 'in' })
expect(view.getByText('Loading store...')).toBeTruthy() expect(view.getByText('Loading store...')).toBeTruthy()
}) })
it('ASTOREEDIT-02: an unknown store shows "Store not found"', () => { it('ASTOREEDIT-02: an unknown store shows "Store not found"', async () => {
setProcedure('admin.store.getStoreById', { data: {} }) setProcedure('admin.store.getStoreById', { data: {} })
const view = renderEdit() const view = await renderEdit()
expect(view.getByText('Store not found')).toBeTruthy() expect(view.getByText('Store not found')).toBeTruthy()
}) })
it('ASTOREEDIT-03: prefills name, description, image and products', () => { it('ASTOREEDIT-03: prefills name, description, image and products', async () => {
const view = renderEdit() const view = await renderEdit()
expect(view.getByText('Edit Store')).toBeTruthy() expect(view.getByText('Edit Store')).toBeTruthy()
expect(view.getByTestId('store-name-input').props.value).toBe(STORE_1.name) expect(view.getByTestId('store-name-input').props.value).toBe(STORE_1.name)
@ -97,12 +106,12 @@ describe('Edit store (ASTOREEDIT-01..12)', () => {
setProcedure('admin.store.updateStore', { setProcedure('admin.store.updateStore', {
data: { store: STORE_1, message: 'Store updated' }, data: { store: STORE_1, message: 'Store updated' },
}) })
const view = renderEdit() const view = await renderEdit()
fireEvent.changeText(view.getByTestId('store-name-input'), 'Renamed Store') fireEvent.changeText(view.getByTestId('store-name-input'), 'Renamed Store')
fireEvent.press(view.getByTestId('store-submit-button')) fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
await waitFor(() => {
expect(lastMutationInput('admin.store.updateStore')).toEqual({ expect(lastMutationInput('admin.store.updateStore')).toEqual({
id: 1, id: 1,
name: 'Renamed Store', name: 'Renamed Store',
@ -111,36 +120,43 @@ describe('Edit store (ASTOREEDIT-01..12)', () => {
imageUrl: undefined, imageUrl: undefined,
}) })
}) })
})
it('ASTOREEDIT-05: removing the existing image submits imageUrl undefined', async () => { it('ASTOREEDIT-05: removing the existing image submits imageUrl undefined', async () => {
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('mock-remove-existing-0')) fireEvent.press(view.getByTestId('mock-remove-existing-0'))
fireEvent.press(view.getByTestId('store-submit-button')) fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
expect(lastMutationInput('admin.store.updateStore')).toEqual( await waitFor(() => {
expect.objectContaining({ id: 1, imageUrl: undefined }) expect(lastMutationInput('admin.store.updateStore')).toEqual({
) id: 1,
name: STORE_1.name,
description: STORE_1.description,
products: PRESELECTED,
})
})
expect(lastMutationInput('admin.store.updateStore')).not.toHaveProperty('imageUrl')
}) })
it('ASTOREEDIT-06: a replacement image is uploaded and its URL submitted', async () => { it('ASTOREEDIT-06: a replacement image is uploaded and its URL submitted', async () => {
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue(PICKED_IMAGE) ;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue(PICKED_IMAGE)
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('mock-add-image')) fireEvent.press(view.getByTestId('mock-add-image'))
await flush() await flush()
fireEvent.press(view.getByTestId('store-submit-button')) fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
await waitFor(() => {
expect(lastMutationInput('admin.store.updateStore')).toEqual( expect(lastMutationInput('admin.store.updateStore')).toEqual(
expect.objectContaining({ id: 1, imageUrl: PRICE_URL }) expect.objectContaining({ id: 1, imageUrl: PRICE_URL })
) )
})
expect(global.fetch).toHaveBeenCalledWith(PRICE_URL, expect.objectContaining({ method: 'PUT' })) expect(global.fetch).toHaveBeenCalledWith(PRICE_URL, expect.objectContaining({ method: 'PUT' }))
}) })
it('ASTOREEDIT-07: the SKUs belonging to the store are preselected', () => { it('ASTOREEDIT-07: the SKUs belonging to the store are preselected', async () => {
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('store-products-selector')) fireEvent.press(view.getByTestId('store-products-selector'))
;[11, 12, 13].forEach((skuId) => { ;[11, 12, 13].forEach((skuId) => {
@ -148,11 +164,11 @@ describe('Edit store (ASTOREEDIT-01..12)', () => {
}) })
}) })
it('ASTOREEDIT-08: a global store renders read-only and has no update action', () => { it('ASTOREEDIT-08: a global store renders read-only and has no update action', async () => {
setProcedure('admin.store.getStoreById', { setProcedure('admin.store.getStoreById', {
data: { store: { ...STORE_GLOBAL, products: [] } }, data: { store: { ...STORE_GLOBAL, products: [] } },
}) })
const view = renderEdit() const view = await renderEdit()
expect(view.getByText('Freshyo Central')).toBeTruthy() expect(view.getByText('Freshyo Central')).toBeTruthy()
expect( expect(
@ -164,35 +180,40 @@ describe('Edit store (ASTOREEDIT-01..12)', () => {
it('ASTOREEDIT-09: an update failure alerts the error', async () => { it('ASTOREEDIT-09: an update failure alerts the error', async () => {
setProcedure('admin.store.updateStore', { mode: 'error', error: new Error('nope') }) setProcedure('admin.store.updateStore', { mode: 'error', error: new Error('nope') })
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('store-submit-button')) fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith('Error', 'nope') expect(alertSpy).toHaveBeenCalledWith('Error', 'nope')
}) })
})
it('ASTOREEDIT-10: a successful update alerts and returns to the list', async () => { it('ASTOREEDIT-10: a successful update alerts and returns to the list', async () => {
setProcedure('admin.store.updateStore', { setProcedure('admin.store.updateStore', {
data: { store: STORE_1, message: 'Store updated' }, data: { store: STORE_1, message: 'Store updated' },
}) })
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('store-submit-button')) fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith('Success', 'Store updated') expect(alertSpy).toHaveBeenCalledWith('Success', 'Store updated')
})
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores')
}) })
it('ASTOREEDIT-11: SKUs from another store are disabled for this store', async () => { it('ASTOREEDIT-11: SKUs from another store are disabled for this store', async () => {
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('store-products-selector')) fireEvent.press(view.getByTestId('store-products-selector'))
fireEvent.press(view.getByTestId('store-products-selector-option-91')) fireEvent.press(view.getByTestId('store-products-selector-option-91'))
fireEvent.press(view.getByTestId('store-products-selector-done')) fireEvent.press(view.getByTestId('store-products-selector-done'))
fireEvent.press(view.getByTestId('store-submit-button')) fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
await waitFor(() => {
expect(lastMutationInput('admin.store.updateStore')).toBeTruthy()
})
const input = lastMutationInput('admin.store.updateStore') const input = lastMutationInput('admin.store.updateStore')
expect(input.products).toEqual(PRESELECTED) expect(input.products).toEqual(PRESELECTED)
@ -200,10 +221,13 @@ describe('Edit store (ASTOREEDIT-01..12)', () => {
}) })
it('ASTOREEDIT-12: the payload selects SKU ids rather than product ids', async () => { it('ASTOREEDIT-12: the payload selects SKU ids rather than product ids', async () => {
const view = renderEdit() const view = await renderEdit()
fireEvent.press(view.getByTestId('store-submit-button')) fireEvent.press(view.getByTestId('store-submit-button'))
await flush(2)
await waitFor(() => {
expect(lastMutationInput('admin.store.updateStore')).toBeTruthy()
})
const input = lastMutationInput('admin.store.updateStore') const input = lastMutationInput('admin.store.updateStore')
expect(input.products).toEqual(PRESELECTED) expect(input.products).toEqual(PRESELECTED)

View file

@ -7,7 +7,7 @@ import { Alert } from 'react-native'
import { fireEvent, act } from '@testing-library/react-native' import { fireEvent, act } from '@testing-library/react-native'
import Stores from '@/app/(drawer)/dashboard/stores/index' import Stores from '@/app/(drawer)/dashboard/stores/index'
import { renderWithProviders } from '../helpers/test-utils' import { renderAndFlush, renderWithProviders } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client' import { setProcedure, lastMutationInput, procedureMutationCalls } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
@ -31,7 +31,7 @@ jest.mock('@react-navigation/native', () => {
}) })
function renderStores() { function renderStores() {
return renderWithProviders(<Stores />, { auth: 'in' }) return renderAndFlush(<Stores />, { auth: 'in' })
} }
describe('Store list (ASTOREUI-01..16)', () => { describe('Store list (ASTOREUI-01..16)', () => {
@ -47,30 +47,31 @@ describe('Store list (ASTOREUI-01..16)', () => {
it('ASTOREUI-01: shows the loading copy', () => { it('ASTOREUI-01: shows the loading copy', () => {
setProcedure('admin.store.getStores', { mode: 'pending' }) setProcedure('admin.store.getStores', { mode: 'pending' })
const view = renderStores() // Loading state is asserted synchronously, before the query settles.
const view = renderWithProviders(<Stores />, { auth: 'in' })
expect(view.getByText('Loading stores...')).toBeTruthy() expect(view.getByText('Loading stores...')).toBeTruthy()
}) })
it('ASTOREUI-02: an error shows Oops! and a retry action', () => { it('ASTOREUI-02: an error shows Oops! and a retry action', async () => {
setProcedure('admin.store.getStores', { mode: 'error', error: new Error('boom') }) setProcedure('admin.store.getStores', { mode: 'error', error: new Error('boom') })
const view = renderStores() const view = await renderStores()
expect(view.getByText('Oops!')).toBeTruthy() expect(view.getByText('Oops!')).toBeTruthy()
fireEvent.press(view.getByText('Retry')) fireEvent.press(view.getByText('Retry'))
}) })
it('ASTOREUI-03: an empty response shows the empty state and the add action', () => { it('ASTOREUI-03: an empty response shows the empty state and the add action', async () => {
setProcedure('admin.store.getStores', { data: { stores: [], count: 0 } }) setProcedure('admin.store.getStores', { data: { stores: [], count: 0 } })
const view = renderStores() const view = await renderStores()
expect(view.getByText('No stores found')).toBeTruthy() expect(view.getByText('No stores found')).toBeTruthy()
fireEvent.press(view.getByTestId('add-store-fab')) fireEvent.press(view.getByTestId('add-store-fab'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores/add') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores/add')
}) })
it('ASTOREUI-04: renders store name, id and image', () => { it('ASTOREUI-04: renders store name, id and image', async () => {
const view = renderStores() const view = await renderStores()
expect(view.getByText('The Freshyo Meat House')).toBeTruthy() expect(view.getByText('The Freshyo Meat House')).toBeTruthy()
expect(view.getByText('ID: #1')).toBeTruthy() expect(view.getByText('ID: #1')).toBeTruthy()
@ -78,8 +79,8 @@ describe('Store list (ASTOREUI-01..16)', () => {
expect(view.getAllByText('View Details')).toHaveLength(2) expect(view.getAllByText('View Details')).toHaveLength(2)
}) })
it('ASTOREUI-05: a global store has no edit/delete action', () => { it('ASTOREUI-05: a global store has no edit/delete action', async () => {
const view = renderStores() const view = await renderStores()
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
expect(view.queryByTestId('delete-store-2')).toBeNull() expect(view.queryByTestId('delete-store-2')).toBeNull()
@ -90,8 +91,8 @@ describe('Store list (ASTOREUI-01..16)', () => {
) )
}) })
it('ASTOREUI-06: edit mode toggles the delete actions', () => { it('ASTOREUI-06: edit mode toggles the delete actions', async () => {
const view = renderStores() const view = await renderStores()
expect(view.queryByTestId('delete-store-1')).toBeNull() expect(view.queryByTestId('delete-store-1')).toBeNull()
@ -103,8 +104,8 @@ describe('Store list (ASTOREUI-01..16)', () => {
expect(view.queryByTestId('delete-store-1')).toBeNull() expect(view.queryByTestId('delete-store-1')).toBeNull()
}) })
it('ASTOREUI-07: tapping a store opens its edit route with the id', () => { it('ASTOREUI-07: tapping a store opens its edit route with the id', async () => {
const view = renderStores() const view = await renderStores()
fireEvent.press(view.getByText('The Freshyo Meat House')) fireEvent.press(view.getByText('The Freshyo Meat House'))
@ -114,16 +115,16 @@ describe('Store list (ASTOREUI-01..16)', () => {
}) })
}) })
it('ASTOREUI-08: a global store never opens the edit route', () => { it('ASTOREUI-08: a global store never opens the edit route', async () => {
const view = renderStores() const view = await renderStores()
fireEvent.press(view.getByText('Freshyo Central')) fireEvent.press(view.getByText('Freshyo Central'))
expect(router.push).not.toHaveBeenCalled() expect(router.push).not.toHaveBeenCalled()
}) })
it('ASTOREUI-09: delete asks for confirmation and Cancel makes no API call', () => { it('ASTOREUI-09: delete asks for confirmation and Cancel makes no API call', async () => {
const view = renderStores() const view = await renderStores()
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
fireEvent.press(view.getByTestId('delete-store-1')) fireEvent.press(view.getByTestId('delete-store-1'))
@ -137,7 +138,7 @@ describe('Store list (ASTOREUI-01..16)', () => {
}) })
it('ASTOREUI-10: confirming delete calls deleteStore and alerts on success', async () => { it('ASTOREUI-10: confirming delete calls deleteStore and alerts on success', async () => {
const view = renderStores() const view = await renderStores()
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
fireEvent.press(view.getByTestId('delete-store-1')) fireEvent.press(view.getByTestId('delete-store-1'))
@ -154,7 +155,7 @@ describe('Store list (ASTOREUI-01..16)', () => {
it('ASTOREUI-11: a failed delete alerts with the error message', async () => { it('ASTOREUI-11: a failed delete alerts with the error message', async () => {
setProcedure('admin.store.deleteStore', { mode: 'error', error: new Error('nope') }) setProcedure('admin.store.deleteStore', { mode: 'error', error: new Error('nope') })
const view = renderStores() const view = await renderStores()
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
fireEvent.press(view.getByTestId('delete-store-1')) fireEvent.press(view.getByTestId('delete-store-1'))
@ -169,7 +170,7 @@ describe('Store list (ASTOREUI-01..16)', () => {
it('ASTOREUI-12: a pending delete keeps the card and shows no success alert', async () => { it('ASTOREUI-12: a pending delete keeps the card and shows no success alert', async () => {
setProcedure('admin.store.deleteStore', { mode: 'pending' }) setProcedure('admin.store.deleteStore', { mode: 'pending' })
const view = renderStores() const view = await renderStores()
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
fireEvent.press(view.getByTestId('delete-store-1')) fireEvent.press(view.getByTestId('delete-store-1'))
@ -183,33 +184,34 @@ describe('Store list (ASTOREUI-01..16)', () => {
expect(alertSpy).not.toHaveBeenCalledWith('Success', 'Store deleted successfully') expect(alertSpy).not.toHaveBeenCalledWith('Success', 'Store deleted successfully')
}) })
it('ASTOREUI-13: the add FAB opens the add route', () => { it('ASTOREUI-13: the add FAB opens the add route', async () => {
const view = renderStores() const view = await renderStores()
fireEvent.press(view.getByTestId('add-store-fab')) fireEvent.press(view.getByTestId('add-store-fab'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores/add') expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/stores/add')
}) })
it('ASTOREUI-14: the page registers a focus callback that triggers a refetch', () => { it('ASTOREUI-14: the page registers a focus callback that triggers a refetch', async () => {
renderStores() await renderStores()
expect(mockFocusCallbacks).toHaveLength(1) const callbacks = [...new Set(mockFocusCallbacks)]
expect(() => mockFocusCallbacks[0]()).not.toThrow() expect(callbacks).toHaveLength(1)
expect(() => callbacks[0]()).not.toThrow()
}) })
it('ASTOREUI-15: a store without an image renders its fallback without crashing', () => { it('ASTOREUI-15: a store without an image renders its fallback without crashing', async () => {
const view = renderStores() const view = await renderStores()
expect(view.getByText('Freshyo Central')).toBeTruthy() expect(view.getByText('Freshyo Central')).toBeTruthy()
}) })
it('ASTOREUI-16: a long store name is truncated to a single line', () => { it('ASTOREUI-16: a long store name is truncated to a single line', async () => {
const longName = 'The Freshyo Meat House With An Extremely Long Branch Name' const longName = 'The Freshyo Meat House With An Extremely Long Branch Name'
setProcedure('admin.store.getStores', { setProcedure('admin.store.getStores', {
data: { stores: [{ ...STORE_1, name: longName }, STORE_GLOBAL], count: 2 }, data: { stores: [{ ...STORE_1, name: longName }, STORE_GLOBAL], count: 2 },
}) })
const view = renderStores() const view = await renderStores()
expect(view.getByText(longName).props.numberOfLines).toBe(1) expect(view.getByText(longName).props.numberOfLines).toBe(1)
}) })

View file

@ -4,12 +4,12 @@
* *
* The incidents fixture is DB-shaped (addedBy is an object); the component * The incidents fixture is DB-shaped (addedBy is an object); the component
* renders `addedBy` directly, so tests feed the procedure-shaped value. * renders `addedBy` directly, so tests feed the procedure-shaped value.
* The shared trpc mock's `refetch` is not observable, so this file wraps the * The real tRPC client + React Query run here; refetches are observed through
* same registry locally to expose it (no harness file is modified). * the recorded procedure calls.
*/ */
import React from 'react' import React from 'react'
import { ActivityIndicator, Alert, StyleSheet } from 'react-native' import { ActivityIndicator, Alert, StyleSheet } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import { tw } from 'common-ui' import { tw } from 'common-ui'
import UserDetails from '@/app/(drawer)/dashboard/user-management/[id]' import UserDetails from '@/app/(drawer)/dashboard/user-management/[id]'
@ -19,41 +19,6 @@ import { lastMutationInput, procedureQueryCalls, setProcedure } from '../mocks/t
import { router, __setParams } from '../mocks/expo-router-mock' import { router, __setParams } from '../mocks/expo-router-mock'
import { USER_DETAILS } from '../fixtures' 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 NOW = new Date().toISOString()
const ORDER_SUMMARY = (over: Record<string, any> = {}) => ({ const ORDER_SUMMARY = (over: Record<string, any> = {}) => ({
@ -120,9 +85,13 @@ describe('User detail (AUD-01..17)', () => {
expect(view.getByText('Error')).toBeTruthy() expect(view.getByText('Error')).toBeTruthy()
expect(view.getByText('boom')).toBeTruthy() expect(view.getByText('boom')).toBeTruthy()
const before = procedureQueryCalls('admin.user.getUserDetails').length
fireEvent.press(view.getByText('Retry')) fireEvent.press(view.getByText('Retry'))
expect(trpcMock.__refetch).toHaveBeenCalled() await waitFor(() => {
expect(procedureQueryCalls('admin.user.getUserDetails').length).toBeGreaterThan(before)
})
}) })
it('AUD-03: an invalid id disables the query and shows the error state', async () => { it('AUD-03: an invalid id disables the query and shows the error state', async () => {
@ -173,14 +142,18 @@ describe('User detail (AUD-01..17)', () => {
const view = renderDetails() const view = renderDetails()
await flush() await flush()
const before = procedureQueryCalls('admin.user.getUserDetails').length
fireEvent.press(view.getByRole('checkbox')) fireEvent.press(view.getByRole('checkbox'))
await flush(2)
await waitFor(() => {
expect(lastMutationInput('admin.user.updateUserSuspension')).toEqual({ expect(lastMutationInput('admin.user.updateUserSuspension')).toEqual({
userId: 5, userId: 5,
isSuspended: true, isSuspended: true,
}) })
expect(trpcMock.__refetch).toHaveBeenCalled() })
await waitFor(() => {
expect(procedureQueryCalls('admin.user.getUserDetails').length).toBeGreaterThan(before)
})
}) })
it('AUD-08: a pending suspension swap shows a spinner instead of the checkbox', async () => { it('AUD-08: a pending suspension swap shows a spinner instead of the checkbox', async () => {
@ -220,10 +193,9 @@ describe('User detail (AUD-01..17)', () => {
setProcedure('admin.user.getUserIncidents', { data: { incidents: [INCIDENT] } }) setProcedure('admin.user.getUserIncidents', { data: { incidents: [INCIDENT] } })
const view = renderDetails() const view = renderDetails()
await flush()
expect(await view.findByText('Late delivery')).toBeTruthy()
expect(view.getByText('User Incidents')).toBeTruthy() expect(view.getByText('User Incidents')).toBeTruthy()
expect(view.getByText('Late delivery')).toBeTruthy()
expect(view.getByText('Added by Admin One')).toBeTruthy() expect(view.getByText('Added by Admin One')).toBeTruthy()
expect(view.getByText('Score: 2')).toBeTruthy() expect(view.getByText('Score: 2')).toBeTruthy()
expect(view.getByText('Order #11')).toBeTruthy() expect(view.getByText('Order #11')).toBeTruthy()

View file

@ -2,14 +2,12 @@
/** /**
* Catalogue section 14.3 — User management (`tests/pages/user-management.test.tsx`). * Catalogue section 14.3 — User management (`tests/pages/user-management.test.tsx`).
* *
* Harness workaround (reported): the shared trpc mock pins `hasNextPage=false` * The real tRPC client + React Query run here; `setUsersPages` feeds the
* and returns a throw-away `fetchNextPage`/`refetch`, so the pagination/footer * infinite query one page per `cursor` through the network mock.
* rows cannot be observed. This file wraps the same procedure registry locally
* (no harness file is modified).
*/ */
import React from 'react' import React from 'react'
import { ActivityIndicator, RefreshControl, StyleSheet } from 'react-native' import { ActivityIndicator, RefreshControl, StyleSheet } from 'react-native'
import { act, fireEvent } from '@testing-library/react-native' import { act, fireEvent, waitFor } from '@testing-library/react-native'
import { tw } from 'common-ui' import { tw } from 'common-ui'
import UserManagement from '@/app/(drawer)/dashboard/user-management/index' import UserManagement from '@/app/(drawer)/dashboard/user-management/index'
@ -19,65 +17,34 @@ import { procedureQueryCalls, setProcedure } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { USER_1, USER_NO_NAME, USER_SUSPENDED } from '../fixtures' import { USER_1, USER_NO_NAME, USER_SUSPENDED } from '../fixtures'
jest.mock('../mocks/trpc-client', () => { type Page = { users: any[]; nextCursor?: number }
const actual = jest.requireActual('../mocks/trpc-client')
const paginationState = { fetchingNextPage: false } function setUsersPages(pages: Page[]) {
const fetchNextPage = jest.fn() setProcedure('admin.user.getAllUsers', {
const refetch = jest.fn(async () => ({ data: undefined })) impl: (input: any) => {
const nodeFor = (path: string) => const cursor = input?.cursor
path.split('.').reduce((node: any, key: string) => node[key], actual.trpc) if (cursor === undefined || cursor === null) return pages[0] ?? { users: [] }
const wrap = (path: string): any => const index = pages.slice(0, -1).findIndex((page) => page.nextCursor === cursor)
new Proxy( return pages[index + 1] ?? { users: [] }
{},
{
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 === 'useInfiniteQuery' && path === 'admin.user.getAllUsers') {
return (input: any, options: any) => {
const result = nodeFor(path).useInfiniteQuery(input, options)
const pages = result.data?.pages ?? []
const lastPage = pages[pages.length - 1]
return {
...result,
refetch,
fetchNextPage,
hasNextPage: Boolean(lastPage?.nextCursor),
isFetchingNextPage: paginationState.fetchingNextPage,
}
}
}
if (prop === 'useQuery' || prop === 'useMutation' || prop === 'useInfiniteQuery') {
return nodeFor(path)[prop]
}
return wrap(path ? `${path}.${prop}` : prop)
}, },
} })
)
return {
...actual,
trpc: wrap(''),
__paginationState: paginationState,
__fetchNextPage: fetchNextPage,
__refetch: refetch,
}
})
const trpcMock = require('../mocks/trpc-client') as any
function setUsersPages(pages: Array<{ users: any[]; nextCursor?: number }>) {
setProcedure('admin.user.getAllUsers', { data: { pages } })
} }
function renderUsers() { function renderUsers() {
return renderWithProviders(<UserManagement />, { auth: 'in' }) 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)', () => { describe('User management (AUM-01..18)', () => {
beforeEach(() => resetAllMocks()) beforeEach(() => resetAllMocks())
@ -97,9 +64,13 @@ describe('User management (AUM-01..18)', () => {
expect(view.getByText('Error')).toBeTruthy() expect(view.getByText('Error')).toBeTruthy()
expect(view.getByText('boom')).toBeTruthy() expect(view.getByText('boom')).toBeTruthy()
const before = procedureQueryCalls('admin.user.getAllUsers').length
fireEvent.press(view.getByText('Retry')) fireEvent.press(view.getByText('Retry'))
expect(trpcMock.__refetch).toHaveBeenCalled() await waitFor(() => {
expect(procedureQueryCalls('admin.user.getAllUsers').length).toBeGreaterThan(before)
})
}) })
it('AUM-03: an empty list shows "No users found"', async () => { it('AUM-03: an empty list shows "No users found"', async () => {
@ -184,25 +155,30 @@ describe('User management (AUM-01..18)', () => {
const input = view.getByPlaceholderText('Search by mobile number...') const input = view.getByPlaceholderText('Search by mobile number...')
fireEvent.changeText(input, ' 987 ') fireEvent.changeText(input, ' 987 ')
await flush() await waitFor(() => {
// Current page code uses `searchTerm || undefined` — no trim is applied.
expect(procedureQueryCalls('admin.user.getAllUsers').pop()).toEqual({ expect(procedureQueryCalls('admin.user.getAllUsers').pop()).toEqual({
limit: 30, limit: 30,
search: ' 987 ', search: ' 987 ',
direction: 'forward',
})
}) })
// Current page code uses `searchTerm || undefined` — no trim is applied.
fireEvent.changeText(input, '') fireEvent.changeText(input, '')
await flush() await flush()
expect(procedureQueryCalls('admin.user.getAllUsers').pop()).toEqual({ // Clearing restores the cached empty-search query, whose request carried
limit: 30, // `search: undefined` (dropped from the wire payload by JSON.stringify).
search: undefined, 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 () => { it('AUM-11: end of list calls fetchNextPage and the appended page is rendered', async () => {
setUsersPages([{ users: [USER_1, USER_SUSPENDED], nextCursor: 6 }]) setUsersPages([
{ users: [USER_1, USER_SUSPENDED], nextCursor: 6 },
{ users: [USER_NO_NAME] },
])
const view = renderUsers() const view = renderUsers()
await flush() await flush()
@ -210,30 +186,30 @@ describe('User management (AUM-01..18)', () => {
expect(view.getByText('9876543210')).toBeTruthy() expect(view.getByText('9876543210')).toBeTruthy()
expect(view.queryByText('No Mobile')).toBeNull() expect(view.queryByText('No Mobile')).toBeNull()
const list = view.UNSAFE_getAllByType(require('react-native').FlatList)[0] await loadNextPage(view)
await act(async () => {
list.props.onEndReached?.({ distanceFromEnd: 0 })
})
expect(trpcMock.__fetchNextPage).toHaveBeenCalled()
await act(async () => {
setUsersPages([{ users: [USER_1, USER_SUSPENDED, USER_NO_NAME], nextCursor: undefined }])
})
await flush()
expect(view.getByText('No Mobile')).toBeTruthy() 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 () => { it('AUM-12: duplicate users across pages are deduped by id', async () => {
setUsersPages([ setUsersPages([
{ users: [USER_1, USER_SUSPENDED] }, { users: [USER_1, USER_SUSPENDED], nextCursor: 6 },
{ users: [USER_1] }, { users: [USER_1] },
]) ])
const view = renderUsers() const view = renderUsers()
await flush() await flush()
expect(view.getByText('Showing 2 users')).toBeTruthy()
await loadNextPage(view)
expect(view.getAllByText('9876543210')).toHaveLength(1) expect(view.getAllByText('9876543210')).toHaveLength(1)
expect(view.getByText('Showing 2 users')).toBeTruthy() expect(view.getByText('Showing 2 users')).toBeTruthy()
}) })
@ -247,6 +223,7 @@ describe('User management (AUM-01..18)', () => {
// MyFlatList always injects its own RefreshControl (refreshAll) after // MyFlatList always injects its own RefreshControl (refreshAll) after
// `{...restProps}`, so the page's refetch handler never runs — current gap. // `{...restProps}`, so the page's refetch handler never runs — current gap.
const clearSpy = jest.spyOn(view.queryClient, 'clear') const clearSpy = jest.spyOn(view.queryClient, 'clear')
const callsBefore = procedureQueryCalls('admin.user.getAllUsers').length
const control = view.UNSAFE_getByType(RefreshControl) const control = view.UNSAFE_getByType(RefreshControl)
await act(async () => { await act(async () => {
control.props.onRefresh?.() control.props.onRefresh?.()
@ -254,18 +231,24 @@ describe('User management (AUM-01..18)', () => {
await flush() await flush()
expect(clearSpy).toHaveBeenCalled() expect(clearSpy).toHaveBeenCalled()
expect(trpcMock.__refetch).not.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 () => { it('AUM-14: the footer spinner shows while the next page is fetching', async () => {
setUsersPages([{ users: [USER_1], nextCursor: 5 }]) setUsersPages([{ users: [USER_1], nextCursor: 5 }])
trpcMock.__paginationState.fetchingNextPage = true
const view = renderUsers() const view = renderUsers()
await flush() 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) expect(view.UNSAFE_getAllByType(ActivityIndicator).length).toBeGreaterThanOrEqual(1)
trpcMock.__paginationState.fetchingNextPage = false
}) })
it('AUM-15: tapping a user opens their detail route', async () => { it('AUM-15: tapping a user opens their detail route', async () => {
@ -285,10 +268,8 @@ describe('User management (AUM-01..18)', () => {
const view = renderUsers() const view = renderUsers()
await flush() await flush()
await act(async () => { setProcedure('admin.user.getAllUsers', { mode: 'error', error: new Error('load-more failed') })
setProcedure('admin.user.getAllUsers', { mode: 'pending' }) await loadNextPage(view)
})
await flush()
expect(view.queryByText('Loading users...')).toBeNull() expect(view.queryByText('Loading users...')).toBeNull()
}) })
@ -300,13 +281,13 @@ describe('User management (AUM-01..18)', () => {
await flush() await flush()
fireEvent.changeText(view.getByPlaceholderText('Search by mobile number...'), '5') fireEvent.changeText(view.getByPlaceholderText('Search by mobile number...'), '5')
await flush() await waitFor(() => {
const searches = procedureQueryCalls('admin.user.getAllUsers').filter( const searches = procedureQueryCalls('admin.user.getAllUsers').filter(
(input) => input?.search === '5' (input) => input?.search === '5'
) )
expect(searches).toHaveLength(1) expect(searches).toHaveLength(1)
expect(searches[0]).toEqual({ limit: 30, search: '5' }) expect(searches[0]).toEqual({ limit: 30, search: '5', direction: 'forward' })
})
}) })
it('AUM-18: an empty search result has no Clear button (current UI)', async () => { it('AUM-18: an empty search result has no Clear button (current UI)', async () => {

View file

@ -5,7 +5,7 @@
*/ */
import React from 'react' import React from 'react'
import { Alert, DeviceEventEmitter, Share } from 'react-native' import { Alert, DeviceEventEmitter, Share } from 'react-native'
import { fireEvent } from '@testing-library/react-native' import { fireEvent, waitFor } from '@testing-library/react-native'
import dayjs from 'dayjs' import dayjs from 'dayjs'
jest.mock('@/components/context/staff-auth-context', () => jest.mock('@/components/context/staff-auth-context', () =>
@ -14,7 +14,7 @@ jest.mock('@/components/context/staff-auth-context', () =>
import VendorSnippets from '@/app/(drawer)/dashboard/vendor-snippets/index' import VendorSnippets from '@/app/(drawer)/dashboard/vendor-snippets/index'
import { __setStaffState } from '../mocks/staff-auth-context' import { __setStaffState } from '../mocks/staff-auth-context'
import { renderWithProviders, flush } from '../helpers/test-utils' import { renderAndFlush, renderWithProviders, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
@ -32,15 +32,19 @@ import {
} from '../fixtures' } from '../fixtures'
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs' import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
function renderPage() { async function renderPage() {
return renderWithProviders(<VendorSnippets />, { auth: false }) const view = await renderAndFlush(<VendorSnippets />, { auth: false })
await flush(2)
return view
} }
function pressIcon(view: ReturnType<typeof renderPage>, name: string, index = 0) { type View = Awaited<ReturnType<typeof renderPage>>
function pressIcon(view: View, name: string, index = 0) {
fireEvent.press(view.UNSAFE_getAllByProps({ name })[index]) fireEvent.press(view.UNSAFE_getAllByProps({ name })[index])
} }
function openMenu(view: ReturnType<typeof renderPage>) { function openMenu(view: View) {
pressIcon(view, 'dots-three-vertical') pressIcon(view, 'dots-three-vertical')
} }
@ -63,21 +67,21 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
it('AVENDUI-01: shows the loading copy', () => { it('AVENDUI-01: shows the loading copy', () => {
setProcedure('admin.vendorSnippets.getAll', { mode: 'pending' }) setProcedure('admin.vendorSnippets.getAll', { mode: 'pending' })
const view = renderPage() const view = renderWithProviders(<VendorSnippets />, { auth: false })
expect(view.getByText('Loading vendor snippets...')).toBeTruthy() expect(view.getByText('Loading vendor snippets...')).toBeTruthy()
}) })
it('AVENDUI-02: a failed query shows the error copy', () => { it('AVENDUI-02: a failed query shows the error copy', async () => {
setProcedure('admin.vendorSnippets.getAll', { mode: 'error', error: new Error('boom') }) setProcedure('admin.vendorSnippets.getAll', { mode: 'error', error: new Error('boom') })
const view = renderPage() const view = await renderPage()
expect(view.getByText('Error loading snippets')).toBeTruthy() expect(view.getByText('Error loading snippets')).toBeTruthy()
}) })
it('AVENDUI-03: an empty result shows the empty state and the add action', () => { it('AVENDUI-03: an empty result shows the empty state and the add action', async () => {
setProcedure('admin.vendorSnippets.getAll', { data: [] }) setProcedure('admin.vendorSnippets.getAll', { data: [] })
const view = renderPage() const view = await renderPage()
expect(view.getByText('No Snippets Yet')).toBeTruthy() expect(view.getByText('No Snippets Yet')).toBeTruthy()
expect( expect(
@ -90,8 +94,8 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
expect(view.getByText('Create Vendor Snippet')).toBeTruthy() expect(view.getByText('Create Vendor Snippet')).toBeTruthy()
}) })
it('AVENDUI-04: a snippet card shows code, slot, validity, products and share', () => { it('AVENDUI-04: a snippet card shows code, slot, validity, products and share', async () => {
const view = renderPage() const view = await renderPage()
expect(view.getByText('Identifier')).toBeTruthy() expect(view.getByText('Identifier')).toBeTruthy()
expect(view.getByText('ABC123')).toBeTruthy() expect(view.getByText('ABC123')).toBeTruthy()
@ -107,7 +111,7 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
expect(view.getByText('View Slot')).toBeTruthy() expect(view.getByText('View Slot')).toBeTruthy()
}) })
it('AVENDUI-05: an expired snippet is badged as expired', () => { it('AVENDUI-05: an expired snippet is badged as expired', async () => {
const expired = { const expired = {
...SNIPPET_1, ...SNIPPET_1,
validTill: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), validTill: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
@ -115,19 +119,19 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
setProcedure('admin.vendorSnippets.getAll', { setProcedure('admin.vendorSnippets.getAll', {
data: [expired], data: [expired],
}) })
const view = renderPage() const view = await renderPage()
expect(view.getByText('Expired')).toBeTruthy() expect(view.getByText('Expired')).toBeTruthy()
expect(view.queryByText('Active')).toBeNull() expect(view.queryByText('Active')).toBeNull()
}) })
it('AVENDUI-06: sharing a snippet without an access URL alerts', () => { it('AVENDUI-06: sharing a snippet without an access URL alerts', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'dismissedAction' } as any) const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'dismissedAction' } as any)
setProcedure('admin.vendorSnippets.getAll', { setProcedure('admin.vendorSnippets.getAll', {
data: [{ ...SNIPPET_1, accessUrl: null }], data: [{ ...SNIPPET_1, accessUrl: null }],
}) })
const view = renderPage() const view = await renderPage()
fireEvent.press(view.getByText('Share')) fireEvent.press(view.getByText('Share'))
@ -138,17 +142,17 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
it('AVENDUI-07: sharing a snippet hands the access URL to the share sheet', async () => { it('AVENDUI-07: sharing a snippet hands the access URL to the share sheet', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'sharedAction' } as any) const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'sharedAction' } as any)
const view = renderPage() const view = await renderPage()
fireEvent.press(view.getByText('Share')) fireEvent.press(view.getByText('Share'))
await flush() await waitFor(() => {
expect(shareSpy).toHaveBeenCalledWith({ message: 'https://access.test/ABC123' }) expect(shareSpy).toHaveBeenCalledWith({ message: 'https://access.test/ABC123' })
})
expect(alertSpy).not.toHaveBeenCalled() expect(alertSpy).not.toHaveBeenCalled()
}) })
it('AVENDUI-08: the products count opens the product list dialog', () => { it('AVENDUI-08: the products count opens the product list dialog', async () => {
const view = renderPage() const view = await renderPage()
fireEvent.press(view.getByText('1 Items')) fireEvent.press(view.getByText('1 Items'))
@ -156,8 +160,8 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
expect(view.getByText('Chicken Breast - 500g')).toBeTruthy() expect(view.getByText('Chicken Breast - 500g')).toBeTruthy()
}) })
it('AVENDUI-09: the View Slot action is currently inert', () => { it('AVENDUI-09: the View Slot action is currently inert', async () => {
const view = renderPage() const view = await renderPage()
fireEvent.press(view.getByText('View Slot')) fireEvent.press(view.getByText('View Slot'))
@ -168,17 +172,18 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
it('AVENDUI-10: the add button creates a snippet and refetches', async () => { it('AVENDUI-10: the add button creates a snippet and refetches', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = renderPage() const view = await renderPage()
pressIcon(view, 'add') pressIcon(view, 'add')
await flush(2)
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'NEWCODE') fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'NEWCODE')
fireEvent.press(view.getByText('Is Permanent?')) fireEvent.press(view.getByText('Is Permanent?'))
fireEvent.press(view.getByText('Select products')) fireEvent.press(view.getByText('Select products'))
fireEvent.press(view.getByText('Chicken Breast - 500g')) fireEvent.press(view.getByText('Chicken Breast - 500g'))
fireEvent.press(view.getByText('Done')) fireEvent.press(view.getByText('Done'))
fireEvent.press(view.getByTestId('snippet-submit-button')) fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush()
await waitFor(() => {
expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({ expect(lastMutationInput('admin.vendorSnippets.create')).toEqual({
snippetCode: 'NEWCODE', snippetCode: 'NEWCODE',
slotId: undefined, slotId: undefined,
@ -186,15 +191,18 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
skuIds: [11], skuIds: [11],
validTill: undefined, validTill: undefined,
}) })
})
expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully') expect(alertSpy).toHaveBeenCalledWith('Success', 'Vendor snippet created successfully')
// onSuccess closes the form and returns to the list. // onSuccess closes the form and returns to the list.
await waitFor(() => {
expect(view.queryByText('Create Vendor Snippet')).toBeNull() expect(view.queryByText('Create Vendor Snippet')).toBeNull()
})
expect(view.getByText('ABC123')).toBeTruthy() expect(view.getByText('ABC123')).toBeTruthy()
}) })
it('AVENDUI-11: Edit opens a prefilled form and updates the snippet', async () => { it('AVENDUI-11: Edit opens a prefilled form and updates the snippet', async () => {
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = renderPage() const view = await renderPage()
openMenu(view) openMenu(view)
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
@ -203,8 +211,8 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
expect(view.getByDisplayValue('ABC123')).toBeTruthy() expect(view.getByDisplayValue('ABC123')).toBeTruthy()
fireEvent.press(view.getByTestId('snippet-submit-button')) fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush()
await waitFor(() => {
expect(lastMutationInput('admin.vendorSnippets.update')).toEqual({ expect(lastMutationInput('admin.vendorSnippets.update')).toEqual({
id: 1, id: 1,
updates: { updates: {
@ -216,10 +224,11 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
}, },
}) })
}) })
})
it('AVENDUI-12: Delete confirms then deletes and refetches', async () => { it('AVENDUI-12: Delete confirms then deletes and refetches', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
const view = renderPage() const view = await renderPage()
openMenu(view) openMenu(view)
fireEvent.press(view.getByText('Delete')) fireEvent.press(view.getByText('Delete'))
@ -232,27 +241,29 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
expect(procedureMutationCalls('admin.vendorSnippets.delete')).toHaveLength(0) expect(procedureMutationCalls('admin.vendorSnippets.delete')).toHaveLength(0)
confirmDelete(alertSpy) confirmDelete(alertSpy)
await flush() await waitFor(() => {
expect(lastMutationInput('admin.vendorSnippets.delete')).toEqual({ id: 1 }) expect(lastMutationInput('admin.vendorSnippets.delete')).toEqual({ id: 1 })
}) })
})
it('AVENDUI-13: a failing create/update/delete surfaces an alert', async () => { it('AVENDUI-13: a failing create/update/delete surfaces an alert', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
setProcedure('admin.vendorSnippets.create', { mode: 'error', error: new Error('save failed') }) setProcedure('admin.vendorSnippets.create', { mode: 'error', error: new Error('save failed') })
setProcedure('admin.vendorSnippets.update', { mode: 'error', error: new Error('update failed') }) setProcedure('admin.vendorSnippets.update', { mode: 'error', error: new Error('update failed') })
const view = renderPage() const view = await renderPage()
pressIcon(view, 'add') pressIcon(view, 'add')
await flush(2)
fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'NEWCODE') fireEvent.changeText(view.getByPlaceholderText('Enter snippet code'), 'NEWCODE')
fireEvent.press(view.getByText('Is Permanent?')) fireEvent.press(view.getByText('Is Permanent?'))
fireEvent.press(view.getByText('Select products')) fireEvent.press(view.getByText('Select products'))
fireEvent.press(view.getByText('Chicken Breast - 500g')) fireEvent.press(view.getByText('Chicken Breast - 500g'))
fireEvent.press(view.getByText('Done')) fireEvent.press(view.getByText('Done'))
fireEvent.press(view.getByTestId('snippet-submit-button')) fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush()
await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith('Error', 'save failed') expect(alertSpy).toHaveBeenCalledWith('Error', 'save failed')
})
// The failed create keeps the form open; close it and fail an update too. // The failed create keeps the form open; close it and fail an update too.
fireEvent.press(view.getByText('✕')) fireEvent.press(view.getByText('✕'))
@ -260,23 +271,26 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
openMenu(view) openMenu(view)
fireEvent.press(view.getByText('Edit')) fireEvent.press(view.getByText('Edit'))
fireEvent.press(view.getByTestId('snippet-submit-button')) fireEvent.press(view.getByTestId('snippet-submit-button'))
await flush()
await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith('Error', 'update failed') expect(alertSpy).toHaveBeenCalledWith('Error', 'update failed')
}) })
})
it('AVENDUI-14: View Orders fetches by snippet code and opens the orders view', async () => { it('AVENDUI-14: View Orders fetches by snippet code and opens the orders view', async () => {
setProcedure('admin.vendorSnippets.getOrdersBySnippet', { data: SNIPPET_ORDERS }) setProcedure('admin.vendorSnippets.getOrdersBySnippet', { data: SNIPPET_ORDERS })
const view = renderPage() const view = await renderPage()
openMenu(view) openMenu(view)
fireEvent.press(view.getByText('View Orders')) fireEvent.press(view.getByText('View Orders'))
await flush() await flush(2)
expect(lastProcedureInput('admin.vendorSnippets.getOrdersBySnippet')).toEqual({ expect(lastProcedureInput('admin.vendorSnippets.getOrdersBySnippet')).toEqual({
snippetCode: 'ABC123', snippetCode: 'ABC123',
}) })
await waitFor(() => {
expect(view.getByText('Orders for "ABC123"')).toBeTruthy() expect(view.getByText('Orders for "ABC123"')).toBeTruthy()
})
expect(view.getByText('ORD-1011')).toBeTruthy() expect(view.getByText('ORD-1011')).toBeTruthy()
}) })
@ -286,13 +300,14 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
mode: 'error', mode: 'error',
error: new Error('orders boom'), error: new Error('orders boom'),
}) })
const view = renderPage() const view = await renderPage()
openMenu(view) openMenu(view)
fireEvent.press(view.getByText('View Orders')) fireEvent.press(view.getByText('View Orders'))
await flush()
await waitFor(() => {
expect(alertSpy).toHaveBeenCalledWith('Error', 'orders boom') expect(alertSpy).toHaveBeenCalledWith('Error', 'orders boom')
})
expect(view.getByText('ABC123')).toBeTruthy() expect(view.getByText('ABC123')).toBeTruthy()
}) })
@ -300,20 +315,21 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
setProcedure('admin.vendorSnippets.getOrdersBySnippet', { setProcedure('admin.vendorSnippets.getOrdersBySnippet', {
data: { ...SNIPPET_ORDERS, data: [] }, data: { ...SNIPPET_ORDERS, data: [] },
}) })
const view = renderPage() const view = await renderPage()
openMenu(view) openMenu(view)
fireEvent.press(view.getByText('View Orders')) fireEvent.press(view.getByText('View Orders'))
await flush()
await waitFor(() => {
expect(view.getByText('No matching orders')).toBeTruthy() expect(view.getByText('No matching orders')).toBeTruthy()
}) })
})
it('AVENDUI-17: a snippet without an access URL/slot renders without crashing', () => { it('AVENDUI-17: a snippet without an access URL/slot renders without crashing', async () => {
setProcedure('admin.vendorSnippets.getAll', { setProcedure('admin.vendorSnippets.getAll', {
data: [{ ...SNIPPET_1, slot: null, validTill: null, isPermanent: true }], data: [{ ...SNIPPET_1, slot: null, validTill: null, isPermanent: true }],
}) })
const view = renderPage() const view = await renderPage()
expect(view.getByText('ABC123')).toBeTruthy() expect(view.getByText('ABC123')).toBeTruthy()
expect(view.getByText('Permanent')).toBeTruthy() expect(view.getByText('Permanent')).toBeTruthy()
@ -324,7 +340,7 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
it('AVENDUI-18: the refresh shortcut is wired to refetch the list', async () => { it('AVENDUI-18: the refresh shortcut is wired to refetch the list', async () => {
const addListener = jest.spyOn(DeviceEventEmitter, 'addListener') const addListener = jest.spyOn(DeviceEventEmitter, 'addListener')
const view = renderPage() const view = await renderPage()
// useManualRefresh subscribes the query refetch to REFRESH_EVENT. // useManualRefresh subscribes the query refetch to REFRESH_EVENT.
const refreshSubscriptions = addListener.mock.calls.filter( const refreshSubscriptions = addListener.mock.calls.filter(
@ -337,13 +353,14 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
data: [{ ...SNIPPET_1, snippetCode: 'REFRESHED' }], data: [{ ...SNIPPET_1, snippetCode: 'REFRESHED' }],
}) })
DeviceEventEmitter.emit(REFRESH_EVENT) DeviceEventEmitter.emit(REFRESH_EVENT)
await flush()
await waitFor(() => {
expect(view.getByText('REFRESHED')).toBeTruthy() expect(view.getByText('REFRESHED')).toBeTruthy()
}) })
})
it('AVENDUI-19: the snippet menu exposes copy/edit/view/delete', () => { it('AVENDUI-19: the snippet menu exposes copy/edit/view/delete', async () => {
const view = renderPage() const view = await renderPage()
openMenu(view) openMenu(view)
@ -354,9 +371,9 @@ describe('Vendor snippets page (AVENDUI-01..20)', () => {
expect(view.getByText('Delete')).toBeTruthy() expect(view.getByText('Delete')).toBeTruthy()
}) })
it('AVENDUI-20: with no snippets the add action still creates one', () => { it('AVENDUI-20: with no snippets the add action still creates one', async () => {
setProcedure('admin.vendorSnippets.getAll', { data: [] }) setProcedure('admin.vendorSnippets.getAll', { data: [] })
const view = renderPage() const view = await renderPage()
expect(view.getByText('No Snippets Yet')).toBeTruthy() expect(view.getByText('No Snippets Yet')).toBeTruthy()
pressIcon(view, 'add') pressIcon(view, 'add')

View file

@ -7,10 +7,15 @@
* globals that every suite needs. * globals that every suite needs.
*/ */
// Presigned uploads (useUploadToObjectStorage) go through the global fetch. import { configure } from '@testing-library/react-native'
if (typeof global.fetch !== 'function') { import { installTrpcNetworkMock } from './mocks/trpc-client'
;(global as any).fetch = jest.fn(async () => ({ ok: true, status: 200 }))
} // The real tRPC client + React Query settle over several ticks. Under the full
// parallel suite a 1s `waitFor` budget is too tight, so give async utils 5s.
configure({ asyncUtilTimeout: 5000 })
// The REAL tRPC client runs in tests; only the network response is faked.
installTrpcNetworkMock()
// Silence noisy console output that the app logs during render. // Silence noisy console output that the app logs during render.
const IGNORED_CONSOLE = [ const IGNORED_CONSOLE = [

View file

@ -0,0 +1,85 @@
/**
* TEST-ONLY unit tests for the Durable Object *scheduling wrapper*.
*
* `tests/unit/cache-creator.test.ts` covers the DO class itself (debounce,
* coalescing, routing, alarm, /clear). This file covers the logic around it —
* `scheduleStoreInitialization` in `src/stores/store-initializer.ts`:
*
* - the `ENABLE_TEST_ROUTES` bypass (no binding access in tests),
* - the missing-binding guard,
* - the `store-init` instance name,
* - `/schedule?regionId=<id>` vs `/schedule` (global) URL construction,
* - swallowing scheduling failures so a mutation never fails because of cache.
*
* The binding is faked through `globalThis.ENV`, so no worker/server is needed.
*/
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
type FakeEnv = Record<string, any>
function setEnv(env: FakeEnv) {
;(globalThis as any).ENV = env
}
function makeBinding() {
const fetch = jest.fn(async () => new Response('OK'))
const stub = { fetch }
const get = jest.fn(() => stub)
const idFromName = jest.fn(() => 'instance-id')
return { binding: { idFromName, get }, idFromName, get, fetch }
}
afterEach(() => {
delete (globalThis as any).ENV
})
describe('scheduleStoreInitialization (DO wrapper)', () => {
it('does not touch the DO binding when ENABLE_TEST_ROUTES is on', async () => {
const { binding, idFromName, get, fetch } = makeBinding()
setEnv({ ENABLE_TEST_ROUTES: 'true', CACHE_CREATOR: binding })
await scheduleStoreInitialization(1)
expect(idFromName).not.toHaveBeenCalled()
expect(get).not.toHaveBeenCalled()
expect(fetch).not.toHaveBeenCalled()
})
it('returns without throwing when the binding is absent', async () => {
setEnv({})
await expect(scheduleStoreInitialization(1)).resolves.toBeUndefined()
})
it('targets the single `store-init` instance with the region id', async () => {
const { binding, idFromName, get, fetch } = makeBinding()
setEnv({ CACHE_CREATOR: binding })
await scheduleStoreInitialization(7)
expect(idFromName).toHaveBeenCalledWith('store-init')
expect(get).toHaveBeenCalledWith('instance-id')
expect(fetch).toHaveBeenCalledWith('https://cache-creator/schedule?regionId=7', {
method: 'POST',
})
})
it('omits regionId for a global (all-regions) request', async () => {
const { binding, fetch } = makeBinding()
setEnv({ CACHE_CREATOR: binding })
await scheduleStoreInitialization()
expect(fetch).toHaveBeenCalledWith('https://cache-creator/schedule', { method: 'POST' })
})
it('swallows a scheduling failure so the mutation still succeeds', async () => {
const fetch = jest.fn(async () => {
throw new Error('stub fetch failed')
})
setEnv({ CACHE_CREATOR: { idFromName: jest.fn(() => 'id'), get: jest.fn(() => ({ fetch })) } })
await expect(scheduleStoreInitialization(1)).resolves.toBeUndefined()
expect(fetch).toHaveBeenCalledTimes(1)
})
})

243
apps/test-improvements.md Normal file
View file

@ -0,0 +1,243 @@
# Test improvements
## Summary and scope
The suites have broad feature coverage. The main weakness is that some tests give more confidence than they should—not a shortage of test cases. Strengthen those before adding more screen-rendering tests.
This report is based on a static review of tests, harnesses, and relevant implementation code in `user-ui`, `admin-ui`, and `backend`. No tests were run and no application or test code was changed. Findings about missing coverage are based on the inspected suites, not measured runtime coverage. OTP and push notifications are excluded per `AGENTS.md`.
Paths below are relative to this file's directory (`apps/`). Line references describe the files at review time and may move.
## 1. Biggest coverage gaps
### A. The real cache pipeline is largely bypassed
Many backend cache tests now call test-only scaffold endpoints rather than fetching the actual published cache files.
Examples:
- `backend/tests/helpers/cache.ts:76`
- `backend/tests/api/cache-products.test.ts:71`
These prove that the backend can construct the right document, but not that:
- A mutation schedules the rebuild.
- The Durable Object runs it.
- Storage receives every file.
- Discovery advertises a readable version.
- Public/CDN responses contain the latest data.
- A global edit reaches every region.
The Durable Object unit tests are useful, but mock `initializeAllStores`, so they do not close that gap.
Add a small real-pipeline integration suite covering:
1. Regional product create/update/delete → public cache changes.
2. Global update → both regions change.
3. Store detail files exist at the advertised version.
4. Temporary 404 → eventual successful read.
5. Failed rebuild → recovery without losing pending work.
Keep the scaffold tests—they are valuable—but do not describe them as full cache end-to-end coverage.
### B. UI tests mostly bypass the real tRPC/React Query lifecycle
Both UI mocks replace the query hooks themselves:
- `user-ui/tests/mocks/trpc-client.ts:141`
- `admin-ui/tests/mocks/trpc-client.ts:141`
In particular:
- `refetch` does not actually fetch.
- Invalidations only record calls.
- Infinite queries always have `hasNextPage: false`.
- `fetchNextPage` does nothing.
- Mutation callback exceptions are swallowed.
- Per-call mutation `onSettled` is not implemented.
Consequently, these suites cannot reliably establish pagination, cache refresh, or mutation lifecycle correctness.
Add a few integration tests using real tRPC hooks and React Query, mocking HTTP responses instead. Prioritize:
- Mutation → invalidation → visibly updated screen.
- First page → next page → no duplicate request.
- Failed refresh retains existing data and can recover.
- Mutation completion clears pending state.
- Logout while a request is pending.
There is no need to rewrite every page test.
### C. No connected customer/admin journey
Individual screens and backend procedures are tested separately, but the seams between them remain exposed.
A concrete example:
- `admin-ui/tests/pages/orders.test.tsx:240` accepts navigation to an `ORD-...` identifier.
- `admin-ui/tests/pages/order-details.test.tsx:43` mounts details with numeric `'11'`.
- The actual details page uses `parseInt(id)`.
Those separate tests do not prove that an order selected from the list can actually be opened.
Add connected journeys:
- Customer: product → cart → checkout → order details.
- Admin: orders list → details → package/deliver → refreshed status.
- Customer subsequently sees the admin's change.
- Product/SKU ID and internal/display order ID remain correct throughout.
Use actual API-shaped responses, not independently adapted fixtures.
## 2. Missing or insufficiently tested edge cases
### user-ui
| Priority | Case to add |
| --- | --- |
| High | **Order succeeds, but the response is lost.** Retry/reopen the app without accidentally creating another order. The double-press test does not cover this. Backend non-idempotency is already documented, so this needs an explicit product decision. |
| High | **Concurrent cart writes.** Two rapid additions, additions from different mounted components, update versus removal, and slot reconciliation versus quantity changes. The storage implementation performs read–modify–write operations, while current cart-hook tests are sequential. |
| High | **Rapid region switching with delayed responses.** A → B → C, then A's products/availability arrive last. Assert actual displayed products, prices, central stores, and persisted carts—not merely the requested URL. |
| High | **Partial region-switch failure.** Snapshot write, cart clear, or restore fails halfway through. Ensure the previous cart is not lost and the new region is not displayed with the old region's items. |
| High | **Checkout becomes stale while open.** Slot closes, product becomes unavailable, coupon expires, address is deleted, or bound/price changes before Place Order. Test a recoverable customer-facing result. |
| Medium | **Background/resume and offline recovery.** Resume after the slot cutoff; network disappears during checkout; connectivity returns without remounting the whole app. |
| Medium | **Storage contains valid JSON with an invalid shape.** Malformed JSON is tested, but also try `null`, `{}`, wrong collection types, missing IDs, and invalid quantities in cart/snapshot data. |
| Medium | **Authentication races.** Logout while profile/login is pending, then a late success arrives; account A logs out and B logs in without A's data returning. |
Existing region-switch, coupon-selection, cart CRUD, and checkout payload tests are good foundations. These additions target timing and recovery rather than repeating happy paths.
### admin-ui
| Priority | Case to add |
| --- | --- |
| High | **Real pagination:** page two succeeds/fails/retries; repeated end-of-list events; filter changes while an old page is pending. |
| High | **Actual delivery reordering:** reorder at least three orders, preserve other staff assignments, switch staff/slot with unsaved changes, and handle an order disappearing after cancellation. |
| High | **Competing edits:** another admin changes stock, prices, packaging, or delivery status while this screen is open. Decide whether stale saves overwrite or conflict. |
| High | **Session persistence failures:** JWT write succeeds but staff write fails; token deletion fails during logout; saved token exists but staff data is missing/corrupt. |
| Medium | **Partial bulk-operation failures:** some banner assignments or other multi-request updates succeed and another fails. Do not report complete success or discard unsaved work. |
| Medium | **Location attachment failures:** permission denied, unavailable location, location timeout, and rejected coordinate update. Delivery-sequence tests currently supply a successful location. |
### backend
#### 1. Failure after persistence has begun
Several transaction tests reject input before the interesting write, or exercise an unrelated happy path. Add controlled failure injection after:
- First split order is inserted.
- Order exists but coupon usage recording fails.
- Default-address clearing occurs.
- An image is claimed but the associated write fails.
Assert persisted invariants afterward. A rejected API response alone does not prove rollback.
#### 2. Stronger concurrency invariants
`backend/tests/api/concurrency.test.ts:77` accepts at least one successful use of a max-one coupon—even if both succeed. The default-address race accepts either one or two defaults.
These do not protect the intended invariants. Test:
- Exactly one allowed coupon consumption.
- Exactly one default address.
- No duplicate unique entities after concurrent creation.
- Concurrent first orders do not both receive first-order-only benefits.
#### 3. Durable Object failure/restart boundaries
Extend `backend/tests/unit/cache-creator.test.ts` with:
- Alarm fires exactly at the debounce deadline.
- Rebuild rejects after pending state is cleared.
- New schedule arrives during rebuilding.
- Instance restarts with persisted pending work.
- One region fails while others remain pending.
#### 4. Flash-delivery scheduler
No tests were found for `backend/src/lib/flash-delivery-cron.ts`. Cover:
- On/off cron mapping.
- UTC/IST interpretation.
- Unknown cron.
- Every bound being updated.
- Constants/KV refresh.
#### 5. More demanding pricing combinations
Basic stacking and rounding are covered. Add:
- Percentage then flat versus flat then percentage through the API.
- Duplicate coupon IDs.
- Unequal split orders with rounding remainders.
- Targeted coupons across multiple slots.
- Exact threshold/max-discount boundaries.
- Partial cancellation of the sub-order carrying delivery/coupon usage.
Assert that discounts and totals reconcile across every sub-order.
#### 6. Upload security boundaries
Existing tests cover fabricated and already-claimed keys. Add:
- Another principal/region's unclaimed key.
- Unrelated `deletedImageKeys`.
- Wrong upload context.
- Actual expired signatures.
- Simultaneous same-MIME key generation.
#### 7. Existing sessions after staff changes
Staff move/delete tests verify records, but not previously issued sessions. Verify old tokens after reassignment/removal, including region isolation.
#### 8. Production configuration safety
Verify test-only cache/rebuild/tracker-reset routes are unavailable when `ENABLE_TEST_ROUTES` is unset or false.
## 3. Tests to replace, merge, or downgrade
### Concrete false-confidence tests
| Test | Problem | Better replacement |
| --- | --- | --- |
| `admin-ui/tests/pages/login.test.tsx:179` — `ALOGIN-14` | Says “storage save failure” but never injects a storage failure. | Reject the relevant storage write and assert consistent auth/storage/navigation state. |
| `admin-ui/tests/pages/delivery-sequences.test.tsx:148` — `ADSEQ-10/11` | “Reorders” a single item into the same order. | Move `[11,12,13]` to `[13,11,12]`; assert displayed and submitted order. |
| `admin-ui/tests/pages/orders.test.tsx:423` — `AORDUI-30` | Pagination test only exercises “no next page.” | Fetch and append a genuine second page. Keep the no-next-page guard as a separate case. |
| `admin-ui/tests/pages/orders.test.tsx:433` — `AORDUI-31/32` | Refresh handler exists/screen survives; no proof data was refetched. | Change server response and verify the new data appears. |
| `backend/tests/api/cache-products.test.ts:530` — `CACHE-48` | Global-edit case performs a global read. | Actual global write followed by convergence across regions. |
| `backend/tests/api/concurrency.test.ts:215` — `CONC-05` | Global-versus-regional scheduling case never schedules a global write. | Unit-test the interleaving, plus a small real-pipeline integration check. |
| `backend/tests/api/transactions.test.ts:179` — `TX-06` | Cancels a nonexistent order, then checks a different order survived. | Fail cancellation midway for the same existing order and inspect its state. |
Similarly, “S3 failure cannot be induced, so a valid upload succeeds” is another happy-path test—not failure coverage. Rename/merge it or inject the failure.
### Lower-value tests to consolidate
- Repeated “floating cart/location bar exists” assertions across many pages.
- Simple store setter/getter tests already exercised through meaningful flows.
- SVG counts, exact colors, and long static-copy assertions in `user-ui/tests/components/static-chrome.test.tsx`.
- Multiple live tests proving the same generic request validation or response shape.
- Separate cases for every small assertion from one expensive shared setup.
These are not all useless. Keep representative wiring tests and important legal/payment copy checks. However, “one catalogue row = one test” is creating maintenance overhead without proportional protection.
## 4. Existing tests that deliberately approve bugs
This is not missing coverage, but it deserves attention:
| Behavior | Reference |
| --- | --- |
| User tokens performing admin suspension | `backend/tests/api/auth-matrix.test.ts:618` |
| Suspended users retaining tRPC access | `backend/tests/api/auth-matrix.test.ts:786` |
| Account deletion partially destroying data before failing | `backend/tests/api/user-profile-auth.test.ts:367` |
| Missing availability producing ₹0 product prices | `user-ui/tests/lib/prominent-api-hooks.test.tsx:297` |
| An inert admin Packaged toggle | `admin-ui/tests/pages/orders.test.tsx:206` |
Characterization tests are useful for documenting current behavior. They should not make these behaviors look like accepted requirements. Track them explicitly, then change their expectations alongside fixes.
## 5. Recommended order of work
1. Replace the concrete false-positive tests above.
2. Add real HTTP-level UI integration coverage.
3. Restore a small genuine public-cache pipeline suite.
4. Add cart/region/auth race tests and mid-write failure tests.
5. Consolidate repeated render/style tests.
**Bottom line:** fewer superficial cases, more connected flows, delayed responses, partial failures, and strict persisted-state invariants.

View file

@ -164,3 +164,46 @@ __setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
should re-require the module with `jest.isolateModules`. should re-require the module with `jest.isolateModules`.
- The `expo-router` mock records navigation but never navigates; layout - The `expo-router` mock records navigation but never navigates; layout
primitives render their children. primitives render their children.
---
## Real tRPC client, mocked network (current harness)
The app's **real** `@/src/trpc-client` and **real React Query** run in tests. Only
the network response is faked:
```
real hook → real httpBatchLink → global fetch (tRPC network mock) → procedure registry
```
- `tests/mocks/trpc-client.ts` no longer replaces the client module. It exports the
procedure registry (`setProcedure`, defaults, call recording) and
`installTrpcNetworkMock()`, which `tests/setup.ts` installs on `global.fetch`.
- The mock parses the client's batch request
(`GET /api/trpc/a.b,c.d?batch=1&input=…` / `POST … body {"0":…}`) and answers
with the tRPC batch envelope. `mode: 'pending'` keeps the hook loading;
`mode: 'error'` returns a tRPC error entry.
- `renderWithProviders` wraps with `QueryClientProvider` **and** the real
`trpc.Provider`.
- `lastProcedureInput` / `procedureMutationCalls` are filled from the real
requests. `useUtils().x.invalidate()` is real; the test QueryClient records the
query keys so `procedureInvalidations(path)` still works.
### Assertions are asynchronous
Queries resolve after a tick and mutations settle asynchronously. Prefer:
```tsx
const view = renderWithProviders(<Page />, { auth: 'in' })
expect(await view.findByText('Chicken Breast')).toBeTruthy()
fireEvent.press(view.getByTestId('save'))
await waitFor(() => expect(lastProcedureInput('user.order.updateUserNotes')).toEqual({ … }))
```
`renderAndFlush(ui)` renders and drains the first round of queries when a test
does several synchronous lookups. Check `isLoading` / `Processing…` **before**
awaiting, and never assume a mutation has completed on the next line.
`forceExit` is enabled in `jest.config.js` because a `mode: 'pending'` fixture
leaves the client's request timer open.

View file

@ -49,6 +49,11 @@ jest.mock('@/utils/queryClient', () => ({
default: require('../helpers/test-utils').createTestQueryClient(), default: require('../helpers/test-utils').createTestQueryClient(),
})) }))
// The mocked client above is a single instance for the whole file with
// `staleTime: Infinity`, so a successful query from one case would be replayed
// to the next (e.g. ROOT-04's failing health check). Reset it per case.
const rootQueryClient = require('@/utils/queryClient').default
const fontsMock = useFonts as unknown as jest.Mock const fontsMock = useFonts as unknown as jest.Mock
const SOURCE_VERSION = '1.2.0' const SOURCE_VERSION = '1.2.0'
const DEV = (global as any).__DEV__ const DEV = (global as any).__DEV__
@ -92,6 +97,7 @@ function NotifProbe() {
describe('app shell (ROOT-01..ROOT-29)', () => { describe('app shell (ROOT-01..ROOT-29)', () => {
beforeEach(() => { beforeEach(() => {
resetAllMocks() resetAllMocks()
rootQueryClient.clear()
fontsMock.mockReturnValue([true, null]) fontsMock.mockReturnValue([true, null])
setDev(DEV) setDev(DEV)
}) })

View file

@ -16,7 +16,7 @@ import { fireEvent, waitFor, within, act } from '@testing-library/react-native'
import AddressForm from '@/src/components/AddressForm' import AddressForm from '@/src/components/AddressForm'
import LocationMapStep from '@/src/components/location/LocationMapStep' import LocationMapStep from '@/src/components/location/LocationMapStep'
import constants from '@/src/constants' import constants from '@/src/constants'
import { renderWithProviders, seedRegion } from '../helpers/test-utils' import { renderWithProviders, seedRegion, flush } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
setProcedure, setProcedure,
@ -27,10 +27,8 @@ import { __configure as configureLocation } from '../mocks/expo-location-mock'
import { __snapshot as secureSnapshot } from '../mocks/secure-store-mock' import { __snapshot as secureSnapshot } from '../mocks/secure-store-mock'
import { A1, REGION_1, REGION_2, BOUND_1 } from '../fixtures' import { A1, REGION_1, REGION_2, BOUND_1 } from '../fixtures'
// AddressForm imports `../trpc-client`, which the jest `moduleNameMapper` // The real tRPC client runs; only `global.fetch` is mocked by the harness, so
// (`^(.*/)?src/trpc-client$`) does not catch. Mock the resolved file explicitly // AddressForm's `../trpc-client` import talks to the procedure registry.
// so the component talks to the harness procedure registry.
jest.mock('../../src/trpc-client.ts', () => require('../mocks/trpc-client'))
const MAP_BASE = `${constants.WEB_UI_BASE_URL}/location-selector` const MAP_BASE = `${constants.WEB_UI_BASE_URL}/location-selector`
const PENDING_ADDRESS_KEY = 'freshyo_pending_address' const PENDING_ADDRESS_KEY = 'freshyo_pending_address'
@ -140,10 +138,11 @@ describe('AddressForm', () => {
expect(getByTestId('address-line1').props.value).toBe('12 Main Road') expect(getByTestId('address-line1').props.value).toBe('12 Main Road')
}) })
it('ADDRF-03: a known browsing region preselects the city', () => { it('ADDRF-03: a known browsing region preselects the city', async () => {
denyLocation() denyLocation()
seedRegion(REGION_1, 7) seedRegion(REGION_1, 7)
const { getByText } = renderForm() const { getByText } = renderForm()
await flush()
expect(getByText('Mahabubnagar')).toBeTruthy() expect(getByText('Mahabubnagar')).toBeTruthy()
}) })
@ -208,9 +207,10 @@ describe('AddressForm', () => {
expect(getByText('Attach a location to add address')).toBeTruthy() expect(getByText('Attach a location to add address')).toBeTruthy()
}) })
it('ADDRF-10: opening the city picker lists the regions, "Select in Map" and no empty message', () => { it('ADDRF-10: opening the city picker lists the regions, "Select in Map" and no empty message', async () => {
denyLocation() denyLocation()
const { getByTestId, getByText, queryByText } = renderForm() const { getByTestId, getByText, queryByText } = renderForm()
await flush()
fireEvent.press(getByTestId('address-city')) fireEvent.press(getByTestId('address-city'))
@ -223,6 +223,7 @@ describe('AddressForm', () => {
it('ADDRF-11: picking a city with no location shows the attach-location error', async () => { it('ADDRF-11: picking a city with no location shows the attach-location error', async () => {
denyLocation() denyLocation()
const { getByTestId, getByText } = renderForm() const { getByTestId, getByText } = renderForm()
await flush()
fireEvent.press(getByTestId('address-city')) fireEvent.press(getByTestId('address-city'))
fireEvent.press(getByTestId('address-city-option-2')) fireEvent.press(getByTestId('address-city-option-2'))
@ -277,10 +278,11 @@ describe('AddressForm', () => {
) )
}) })
it('ADDRF-14: "Select in Map" from the city picker opens the map at the first region centre', () => { it('ADDRF-14: "Select in Map" from the city picker opens the map at the first region centre', async () => {
denyLocation() denyLocation()
setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] }) setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] })
const { getByTestId } = renderForm() const { getByTestId } = renderForm()
await flush()
openMapViaCity({ getByTestId } as any) openMapViaCity({ getByTestId } as any)
@ -288,10 +290,11 @@ describe('AddressForm', () => {
expect(webview.props.source.uri).toBe(`${MAP_BASE}?lat=11&lng=22`) expect(webview.props.source.uri).toBe(`${MAP_BASE}?lat=11&lng=22`)
}) })
it('ADDRF-15: the location chooser opens the region picker and marks the current region', () => { it('ADDRF-15: the location chooser opens the region picker and marks the current region', async () => {
denyLocation() denyLocation()
seedRegion(REGION_1, 7) seedRegion(REGION_1, 7)
const { getByTestId, getByText } = renderForm() const { getByTestId, getByText } = renderForm()
await flush()
fireEvent.press(getByTestId('address-attach-location')) fireEvent.press(getByTestId('address-attach-location'))
@ -300,10 +303,11 @@ describe('AddressForm', () => {
expect(getByText('Select a region')).toBeTruthy() expect(getByText('Select a region')).toBeTruthy()
}) })
it('ADDRF-16: picking a region in the chooser opens the map at that region centre', () => { it('ADDRF-16: picking a region in the chooser opens the map at that region centre', async () => {
denyLocation() denyLocation()
setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] }) setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] })
const { getByTestId } = renderForm() const { getByTestId } = renderForm()
await flush()
fireEvent.press(getByTestId('address-attach-location')) fireEvent.press(getByTestId('address-attach-location'))
fireEvent.press(getByTestId('address-map-region-2')) fireEvent.press(getByTestId('address-map-region-2'))
@ -311,10 +315,11 @@ describe('AddressForm', () => {
expect(getByTestId('webview').props.source.uri).toBe(`${MAP_BASE}?lat=33&lng=44`) expect(getByTestId('webview').props.source.uri).toBe(`${MAP_BASE}?lat=33&lng=44`)
}) })
it('ADDRF-17: "Select in Map" from the chooser opens the map at the first region', () => { it('ADDRF-17: "Select in Map" from the chooser opens the map at the first region', async () => {
denyLocation() denyLocation()
setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] }) setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] })
const { getByTestId } = renderForm() const { getByTestId } = renderForm()
await flush()
fireEvent.press(getByTestId('address-attach-location')) fireEvent.press(getByTestId('address-attach-location'))
fireEvent.press(getByTestId('address-map-region-select-in-map')) fireEvent.press(getByTestId('address-map-region-select-in-map'))
@ -322,9 +327,10 @@ describe('AddressForm', () => {
expect(getByTestId('webview').props.source.uri).toBe(`${MAP_BASE}?lat=11&lng=22`) expect(getByTestId('webview').props.source.uri).toBe(`${MAP_BASE}?lat=11&lng=22`)
}) })
it('ADDRF-18: cancelling the region chooser closes it', () => { it('ADDRF-18: cancelling the region chooser closes it', async () => {
denyLocation() denyLocation()
const { getByTestId, queryByTestId } = renderForm() const { getByTestId, queryByTestId } = renderForm()
await flush()
fireEvent.press(getByTestId('address-attach-location')) fireEvent.press(getByTestId('address-attach-location'))
expect(getByTestId('address-map-region-1')).toBeTruthy() expect(getByTestId('address-map-region-1')).toBeTruthy()
@ -559,13 +565,11 @@ describe('AddressForm', () => {
jest.useFakeTimers() jest.useFakeTimers()
fireEvent.press(getByTestId('address-submit')) fireEvent.press(getByTestId('address-submit'))
// The batch link schedules its request on a timer, so drain the timer queue
// (which also flushes the promise chain) instead of bare microtasks.
await act(async () => { await act(async () => {
await Promise.resolve() await jest.advanceTimersByTimeAsync(0)
}) })
await act(async () => {
await Promise.resolve()
})
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1) expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
expect(onSuccess).not.toHaveBeenCalled() expect(onSuccess).not.toHaveBeenCalled()
@ -578,6 +582,7 @@ describe('AddressForm', () => {
jest.advanceTimersByTime(1) jest.advanceTimersByTime(1)
}) })
expect(onSuccess).toHaveBeenCalledWith(A1.id) expect(onSuccess).toHaveBeenCalledWith(A1.id)
jest.useRealTimers()
}) })
it('ADDRF-32: a pending submit shows "Adding..."/"Updating..." and disables submit', async () => { it('ADDRF-32: a pending submit shows "Adding..."/"Updating..." and disables submit', async () => {
@ -607,6 +612,7 @@ describe('AddressForm', () => {
it('ADDRF-33: the map shows "Loading map..." and the step renders its error banner', async () => { it('ADDRF-33: the map shows "Loading map..." and the step renders its error banner', async () => {
denyLocation() denyLocation()
const screen = renderForm() const screen = renderForm()
await flush()
openMapViaChooser(screen as any) openMapViaChooser(screen as any)
expect(screen.getByText('Loading map...')).toBeTruthy() expect(screen.getByText('Loading map...')).toBeTruthy()
@ -640,10 +646,11 @@ describe('AddressForm', () => {
await waitFor(() => expect(resolve).toHaveBeenCalledWith({ lat: 9.9, lng: 8.8 })) await waitFor(() => expect(resolve).toHaveBeenCalledWith({ lat: 9.9, lng: 8.8 }))
}) })
it('ADDRF-35: invalid map messages are ignored', () => { it('ADDRF-35: invalid map messages are ignored', async () => {
denyLocation() denyLocation()
const resolve = spyResolveRegion() const resolve = spyResolveRegion()
const { getByTestId, queryByText } = renderForm() const { getByTestId, queryByText } = renderForm()
await flush()
openMapViaChooser({ getByTestId } as any) openMapViaChooser({ getByTestId } as any)
sendMapMessage({ getByTestId } as any, 'not-json') sendMapMessage({ getByTestId } as any, 'not-json')
@ -655,10 +662,11 @@ describe('AddressForm', () => {
expect(queryByText('Location Attached from Map')).toBeNull() expect(queryByText('Location Attached from Map')).toBeNull()
}) })
it('ADDRF-36: the map URL carries lat/lng query params when a centre is known', () => { it('ADDRF-36: the map URL carries lat/lng query params when a centre is known', async () => {
denyLocation() denyLocation()
setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] }) setProcedure('common.listRegions', { data: [REGION_1_CENTER, REGION_2_CENTER] })
const { getByTestId } = renderForm() const { getByTestId } = renderForm()
await flush()
openMapViaCity({ getByTestId } as any) openMapViaCity({ getByTestId } as any)
@ -667,9 +675,10 @@ describe('AddressForm', () => {
expect(uri).toContain('&lng=22') expect(uri).toContain('&lng=22')
}) })
it('ADDRF-37: the map URL is the bare base URL when no centre is known', () => { it('ADDRF-37: the map URL is the bare base URL when no centre is known', async () => {
denyLocation() denyLocation()
const { getByTestId } = renderForm() const { getByTestId } = renderForm()
await flush()
openMapViaCity({ getByTestId } as any) openMapViaCity({ getByTestId } as any)

View file

@ -30,9 +30,6 @@ import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, REGION_2 } from '../fixtures' import { A1, A2, A3, REGION_1, REGION_2 } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
// `AddressForm` imports the client relatively (`../trpc-client`) which the
// moduleNameMapper does not rewrite; point that resolved path at the shared mock.
jest.mock('../../src/trpc-client.ts', () => require('../mocks/trpc-client'))
jest.mock('@/src/hooks/useRegion', () => ({ jest.mock('@/src/hooks/useRegion', () => ({
useRegion: () => (globalThis as any).__regionHook, useRegion: () => (globalThis as any).__regionHook,
})) }))
@ -212,6 +209,8 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
await act(async () => { await act(async () => {
await confirm.onPress() await confirm.onPress()
}) })
// `confirmRegionSwitch` awaits the cart clear before navigating.
await flush()
expect(useRegionStore.getState().selectedRegionId).toBe(2) expect(useRegionStore.getState().selectedRegionId).toBe(2)
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
alertSpy.mockRestore() alertSpy.mockRestore()
@ -406,6 +405,12 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
}) })
it('CAS-22: the display is query-disabled when signed out and does not crash', async () => { it('CAS-22: the display is query-disabled when signed out and does not crash', async () => {
__setAuthState({ isAuthenticated: false, isLoading: false })
// The real batch link schedules requests on a timer; drain one left over
// from the previous case and clear its record before asserting this render
// issued none.
await flush()
resetAllMocks()
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false }) const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
await flush(2) await flush(2)
expect(getByText('No address selected')).toBeTruthy() expect(getByText('No address selected')).toBeTruthy()

View file

@ -20,6 +20,7 @@ import {
lastProcedureInput, lastProcedureInput,
procedureCallCount, procedureCallCount,
setProcedure, setProcedure,
setRawFetchHandler,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import ComplaintForm from '@/components/ComplaintForm' import ComplaintForm from '@/components/ComplaintForm'
@ -28,13 +29,18 @@ const IMAGE_URL = 'https://cdn.test/photo.jpg'
const PRESIGNED_URL = 'https://upload.test/complaint/abc.jpg' const PRESIGNED_URL = 'https://upload.test/complaint/abc.jpg'
const UPLOADED_KEY = 'abc.jpg' const UPLOADED_KEY = 'abc.jpg'
/**
* Serve the object-store calls (blob read + presigned PUT) through the harness'
* non-tRPC fetch hook. Replacing `global.fetch` outright would bypass the tRPC
* network mock.
*/
function installFetch() { function installFetch() {
const fetchSpy = jest.fn(async () => ({ const fetchSpy = jest.fn(async () => ({
ok: true, ok: true,
status: 200, status: 200,
blob: async () => ({}), blob: async () => ({}),
})) }))
;(global as any).fetch = fetchSpy setRawFetchHandler(fetchSpy as any)
return fetchSpy return fetchSpy
} }
@ -107,9 +113,11 @@ describe('ComplaintForm', () => {
}) })
) )
await waitFor(() =>
expect(alertSpy).toHaveBeenCalledWith('Success', 'Complaint raised successfully') expect(alertSpy).toHaveBeenCalledWith('Success', 'Complaint raised successfully')
)
expect(getByTestId('complaint-body').props.value).toBe('') expect(getByTestId('complaint-body').props.value).toBe('')
expect(onClose).toHaveBeenCalledTimes(1) await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))
expectNoProcedureCall('common.generateUploadUrls') expectNoProcedureCall('common.generateUploadUrls')
}) })
@ -136,12 +144,14 @@ describe('ComplaintForm', () => {
mimeTypes: ['image/jpeg'], mimeTypes: ['image/jpeg'],
}) })
// The blob is read from the picked uri and PUT to the presigned url. // The blob is read from the picked uri and PUT to the presigned url.
expect(fetchSpy).toHaveBeenCalledWith(IMAGE_URL) // (The harness' fetch calls the non-tRPC handler with `(url, init)`, so
// match the read call by URL rather than by an exact argument list.)
expect(fetchSpy.mock.calls.map(([url]: any[]) => url)).toContain(IMAGE_URL)
expect(fetchSpy).toHaveBeenCalledWith( expect(fetchSpy).toHaveBeenCalledWith(
PRESIGNED_URL, PRESIGNED_URL,
expect.objectContaining({ method: 'PUT', headers: { 'Content-Type': 'image/jpeg' } }) expect.objectContaining({ method: 'PUT', headers: { 'Content-Type': 'image/jpeg' } })
) )
expect(onClose).toHaveBeenCalledTimes(1) await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))
}) })
it('CF-05: alerts and does not raise when the upload fails', async () => { it('CF-05: alerts and does not raise when the upload fails', async () => {

View file

@ -44,9 +44,6 @@ import { router } from '../mocks/expo-router-mock'
import { A1, A2, A3, REGION_1, BOUND_1, SLOTS, CONSTS } from '../fixtures' import { A1, A2, A3, REGION_1, BOUND_1, SLOTS, CONSTS } from '../fixtures'
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
// `AddressForm` imports the client relatively (`../trpc-client`) which the
// moduleNameMapper does not rewrite; point that resolved path at the shared mock.
jest.mock('../../src/trpc-client.ts', () => require('../mocks/trpc-client'))
jest.mock('@/src/hooks/useRegion', () => ({ jest.mock('@/src/hooks/useRegion', () => ({
useRegion: () => (globalThis as any).__regionHook, useRegion: () => (globalThis as any).__regionHook,
})) }))
@ -566,7 +563,8 @@ describe('Location components (LOC)', () => {
it('LOC-29: while busy an overlay is shown and the address cards are disabled', async () => { it('LOC-29: while busy an overlay is shown and the address cards are disabled', async () => {
signIn() signIn()
setAddresses([S1, S2]) setAddresses([S1, S2])
setProcedure('common.listRegions', { impl: () => new Promise(() => {}) }) // A never-settling batch keeps `listRegions.fetch()` (and therefore `busy`) pending.
setProcedure('common.listRegions', { mode: 'pending' })
const { getByTestId } = renderWithProviders(<LocationFallbackFlow />, { auth: false }) const { getByTestId } = renderWithProviders(<LocationFallbackFlow />, { auth: false })
await flush(2) await flush(2)
fireEvent.press(getByTestId('location-address-11')) fireEvent.press(getByTestId('location-address-11'))

View file

@ -42,6 +42,14 @@ function advance(ms = 300) {
}) })
} }
/**
* React Query batches observer notifications on a `setTimeout(0)`; with fake
* timers the pending state is only visible after that timer runs.
*/
function settlePendingState() {
advance(1)
}
type GetByTestId = (testId: string) => any type GetByTestId = (testId: string) => any
function openNotesDialog(getByTestId: GetByTestId) { function openNotesDialog(getByTestId: GetByTestId) {
@ -214,6 +222,7 @@ describe('OrderMenu', () => {
openNotesDialog(getByTestId) openNotesDialog(getByTestId)
fireEvent.changeText(getByTestId('order-menu-notes-input'), 'note') fireEvent.changeText(getByTestId('order-menu-notes-input'), 'note')
fireEvent.press(getByTestId('order-menu-save-notes')) fireEvent.press(getByTestId('order-menu-save-notes'))
settlePendingState()
expect(queryByText('Save Instructions')).toBeNull() expect(queryByText('Save Instructions')).toBeNull()
expect(getByTestId('order-menu-save-notes').props.accessibilityState.disabled).toBe(true) expect(getByTestId('order-menu-save-notes').props.accessibilityState.disabled).toBe(true)
@ -223,6 +232,7 @@ describe('OrderMenu', () => {
openCancelDialog(getByTestId) openCancelDialog(getByTestId)
fireEvent.changeText(getByTestId('order-menu-cancel-reason-input'), 'reason') fireEvent.changeText(getByTestId('order-menu-cancel-reason-input'), 'reason')
fireEvent.press(getByTestId('order-menu-confirm-cancel')) fireEvent.press(getByTestId('order-menu-confirm-cancel'))
settlePendingState()
expect(queryByText('Confirm Cancellation')).toBeNull() expect(queryByText('Confirm Cancellation')).toBeNull()
expect(getByTestId('order-menu-confirm-cancel').props.accessibilityState.disabled).toBe(true) expect(getByTestId('order-menu-confirm-cancel').props.accessibilityState.disabled).toBe(true)

View file

@ -19,6 +19,7 @@ import {
setProcedure, setProcedure,
lastProcedureInput, lastProcedureInput,
procedureCallCount, procedureCallCount,
setRawFetchHandler,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
const UPLOAD_URL = 'https://bucket.test/profile/upload-1.jpg' const UPLOAD_URL = 'https://bucket.test/profile/upload-1.jpg'
@ -29,7 +30,10 @@ const picker = ImagePicker.launchImageLibraryAsync as unknown as jest.Mock
let alertSpy: jest.SpyInstance let alertSpy: jest.SpyInstance
/** Replace `global.fetch`: the blob read resolves, the presigned PUT succeeds. */ /**
* Serve the blob read + presigned PUT through the harness' non-tRPC fetch hook.
* Replacing `global.fetch` outright would bypass the tRPC network mock.
*/
function mockFetch() { function mockFetch() {
const fn = jest.fn(async (_url: string, init?: any) => { const fn = jest.fn(async (_url: string, init?: any) => {
if (init?.method === 'PUT') { if (init?.method === 'PUT') {
@ -37,7 +41,7 @@ function mockFetch() {
} }
return { ok: true, status: 200, blob: async () => ({ size: 4 }) } as any return { ok: true, status: 200, blob: async () => ({ size: 4 }) } as any
}) })
;(global as any).fetch = fn setRawFetchHandler(fn as any)
return fn return fn
} }

View file

@ -4,6 +4,8 @@ import { render as rtlRender, RenderResult } from '@testing-library/react-native
import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RefreshProvider } from 'common-ui' import { RefreshProvider } from 'common-ui'
import { AuthProvider } from '@/src/contexts/AuthContext' import { AuthProvider } from '@/src/contexts/AuthContext'
import { trpc, trpcClient } from '@/src/trpc-client'
import { recordQueryInvalidation } from '../mocks/trpc-client'
import { setJsonResponse } from '../mocks/fetch-json' import { setJsonResponse } from '../mocks/fetch-json'
import { __set as setSecureItem, __delete as deleteSecureItem } from '../mocks/secure-store-mock' import { __set as setSecureItem, __delete as deleteSecureItem } from '../mocks/secure-store-mock'
import { import {
@ -31,7 +33,7 @@ import { useRegionStore } from '@/src/store/regionStore'
import { useAddressStore } from '@/src/store/addressStore' import { useAddressStore } from '@/src/store/addressStore'
export function createTestQueryClient(): QueryClient { export function createTestQueryClient(): QueryClient {
return new QueryClient({ const queryClient = new QueryClient({
defaultOptions: { defaultOptions: {
queries: { queries: {
retry: false, retry: false,
@ -42,6 +44,16 @@ export function createTestQueryClient(): QueryClient {
mutations: { retry: false }, mutations: { retry: false },
}, },
}) })
// Record real tRPC invalidations (`useUtils().x.invalidate()`) for the
// existing `procedureInvalidations(path)` assertions.
const originalInvalidate = queryClient.invalidateQueries.bind(queryClient)
;(queryClient as any).invalidateQueries = ((filters?: any, options?: any) => {
recordQueryInvalidation(filters)
return originalInvalidate(filters, options)
}) as any
return queryClient
} }
type AuthMode = 'in' | 'out' | false type AuthMode = 'in' | 'out' | false
@ -89,6 +101,8 @@ export function renderWithProviders(
if (withRefresh) { if (withRefresh) {
tree = React.createElement(RefreshProvider, { queryClient, children: tree } as any) tree = React.createElement(RefreshProvider, { queryClient, children: tree } as any)
} }
// Real tRPC React hooks need the real client + provider.
tree = React.createElement(trpc.Provider, { client: trpcClient, queryClient, children: tree })
tree = React.createElement(QueryClientProvider, { client: queryClient }, tree) tree = React.createElement(QueryClientProvider, { client: queryClient }, tree)
return tree return tree
} }
@ -108,7 +122,7 @@ export async function renderAndFlush(
} }
/** Await a macrotask so promise chains and effects settle. */ /** Await a macrotask so promise chains and effects settle. */
export async function flush(times = 1) { export async function flush(times = 2) {
const { act } = require('@testing-library/react-native') const { act } = require('@testing-library/react-native')
for (let index = 0; index < times; index += 1) { for (let index = 0; index < times; index += 1) {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop

View file

@ -55,9 +55,6 @@ module.exports = {
], ],
moduleNameMapper: { moduleNameMapper: {
// Manual mocks first (order matters: moduleNameMapper is first-match-wins). // Manual mocks first (order matters: moduleNameMapper is first-match-wins).
'^(.*/)?src/trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^\\./trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^\\.\\./trpc-client$': '<rootDir>/mocks/trpc-client.ts',
'^(.*/)?src/lib/fetch-json$': '<rootDir>/mocks/fetch-json.ts', '^(.*/)?src/lib/fetch-json$': '<rootDir>/mocks/fetch-json.ts',
// Native / platform modules -> shared shims (every copy of a package, root // Native / platform modules -> shared shims (every copy of a package, root
// or packages/ui/node_modules, resolves to the same mock). // or packages/ui/node_modules, resolves to the same mock).
@ -110,4 +107,7 @@ module.exports = {
testTimeout: 20000, testTimeout: 20000,
verbose: false, verbose: false,
maxWorkers: '50%', maxWorkers: '50%',
// Real React Query + the tRPC client can leave pending timers (e.g. a
// `mode: 'pending'` fixture); force the worker down after the run.
forceExit: true,
} }

View file

@ -260,10 +260,24 @@ describe('app helpers', () => {
}) })
it('PENDING-09: concurrent auth events run one sync at a time', async () => { it('PENDING-09: concurrent auth events run one sync at a time', async () => {
setProcedure('user.address.createAddress', { mode: 'pending' })
__set('freshyo_pending_address', JSON.stringify(PENDING_INPUT)) __set('freshyo_pending_address', JSON.stringify(PENDING_INPUT))
__setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER }) __setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER })
// Keep the first create in flight by holding its *response* (a
// `mode: 'pending'` procedure is never recorded by the network mock), so the
// request is observable and a second one would be too.
const networkMock = global.fetch as any
let release!: () => void
const held = new Promise<void>((resolve) => {
release = resolve
})
;(global as any).fetch = jest.fn(async (input: any, init: any) => {
const response = await networkMock(input, init)
if (String(input).includes('user.address.createAddress')) await held
return response
})
try {
const { rerender } = renderWithProviders(<PendingAddressSync />, { auth: false }) const { rerender } = renderWithProviders(<PendingAddressSync />, { auth: false })
await flush(3) await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1) expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
@ -277,6 +291,13 @@ describe('app helpers', () => {
// The in-flight guard holds, so no second create is fired. // The in-flight guard holds, so no second create is fired.
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1) expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
release()
await flush(3)
expect(procedureMutationCalls('user.address.createAddress')).toHaveLength(1)
} finally {
;(global as any).fetch = networkMock
}
}) })
it('PENDING-10: unmounting before the read resolves cancels the sync', async () => { it('PENDING-10: unmounting before the read resolves cancels the sync', async () => {

View file

@ -86,8 +86,11 @@ describe('AuthContext', () => {
}) })
renderWithProviders(<AuthProbe />, { auth: 'in' }) renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.isAuthenticated).toBe(false)) // `isAuthenticated` starts false, so wait for the bootstrap + self read to
expect(ctx.isLoading).toBe(false) // settle (the signed-in state is too short-lived for a poll to catch), then
// assert the failure signed the user out.
await waitFor(() => expect(ctx.isLoading).toBe(false))
expect(ctx.isAuthenticated).toBe(false)
// Current behaviour: deleteAuthToken() is commented out. // Current behaviour: deleteAuthToken() is commented out.
expect(__snapshot().authToken).toBe(TEST_JWT) expect(__snapshot().authToken).toBe(TEST_JWT)
}) })

View file

@ -11,7 +11,8 @@
import * as React from 'react' import * as React from 'react'
import { Text, View } from 'react-native' import { Text, View } from 'react-native'
import { waitFor } from '@testing-library/react-native' import { waitFor } from '@testing-library/react-native'
import { trpc, setProcedure, lastProcedureInput, procedureMutationCalls } from '../mocks/trpc-client' import { trpc } from '@/src/trpc-client'
import { setProcedure, lastProcedureInput, procedureMutationCalls } from '../mocks/trpc-client'
import { fetchJson } from '../mocks/fetch-json' import { fetchJson } from '../mocks/fetch-json'
import { StorageService, StorageServiceCasual } from 'common-ui' import { StorageService, StorageServiceCasual } from 'common-ui'
import { useAllProducts } from '@/src/hooks/prominent-api-hooks' import { useAllProducts } from '@/src/hooks/prominent-api-hooks'

View file

@ -26,7 +26,6 @@ import {
} from '../mocks/fetch-json' } from '../mocks/fetch-json'
import { import {
setProcedure, setProcedure,
clearProcedure,
lastProcedureInput, lastProcedureInput,
procedureCallCount, procedureCallCount,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
@ -132,7 +131,9 @@ describe('prominent API hooks', () => {
}) })
it('API-05: a cached consts payload per bound is a placeholder; corrupt cache is ignored', async () => { it('API-05: a cached consts payload per bound is a placeholder; corrupt cache is ignored', async () => {
clearProcedure('common.essentialConsts') // Keep the request in flight: a procedure that resolves `undefined` lands as
// a successful (empty) query result, which would override placeholderData.
setProcedure('common.essentialConsts', { mode: 'pending' })
// Corrupt cache must not throw and must surface no placeholder. // Corrupt cache must not throw and must surface no placeholder.
setSecureItem('essential_consts_b7', 'not-json') setSecureItem('essential_consts_b7', 'not-json')
@ -151,7 +152,8 @@ describe('prominent API hooks', () => {
}) })
it('API-06: the consts cache is keyed per bound (no cross-bound leak)', async () => { it('API-06: the consts cache is keyed per bound (no cross-bound leak)', async () => {
clearProcedure('common.essentialConsts') // Keep the request in flight so the bound-keyed cache stays the placeholder.
setProcedure('common.essentialConsts', { mode: 'pending' })
setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 })) setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 }))
setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 222 })) setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 222 }))
seedRegion(REGION_1 as any, 8) seedRegion(REGION_1 as any, 8)
@ -330,7 +332,7 @@ describe('prominent API hooks', () => {
}) })
await waitFor(() => expect(jsonCallsFor(productsCacheUrl(2))).toHaveLength(1)) await waitFor(() => expect(jsonCallsFor(productsCacheUrl(2))).toHaveLength(1))
expect(result.current.data).toBeTruthy() await waitFor(() => expect(result.current.data).toBeTruthy())
}) })
it('API-19: useRegionalConsts passes through the essential consts data', async () => { it('API-19: useRegionalConsts passes through the essential consts data', async () => {

View file

@ -16,6 +16,15 @@
*/ */
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
/**
* `installTrpcNetworkMock()` (tests/setup.ts) is installed from the ROOT module
* registry, so `global.fetch` answers from the root copy of the procedure
* registry. Re-requiring the registry inside `jest.isolateModulesAsync` would
* give this file a copy that the network mock never sees; procedure fixtures and
* call recording must go through the root instance.
*/
const networkTrpc = require('../mocks/trpc-client')
async function withFreshModules(fn: (ctx: any) => Promise<void>) { async function withFreshModules(fn: (ctx: any) => Promise<void>) {
await jest.isolateModulesAsync(async () => { await jest.isolateModulesAsync(async () => {
const previousSkip = process.env.RNTL_SKIP_AUTO_CLEANUP const previousSkip = process.env.RNTL_SKIP_AUTO_CLEANUP
@ -24,6 +33,8 @@ async function withFreshModules(fn: (ctx: any) => Promise<void>) {
const React = require('react') const React = require('react')
const rtl = require('@testing-library/react-native') const rtl = require('@testing-library/react-native')
require('../helpers/reset').resetAllMocks() require('../helpers/reset').resetAllMocks()
// Stored procedures/calls live on the root registry (see above).
networkTrpc.resetTrpcMocks()
if (previousSkip === undefined) delete process.env.RNTL_SKIP_AUTO_CLEANUP if (previousSkip === undefined) delete process.env.RNTL_SKIP_AUTO_CLEANUP
else process.env.RNTL_SKIP_AUTO_CLEANUP = previousSkip else process.env.RNTL_SKIP_AUTO_CLEANUP = previousSkip
@ -33,7 +44,7 @@ async function withFreshModules(fn: (ctx: any) => Promise<void>) {
rtl, rtl,
auth: require('../mocks/auth-context'), auth: require('../mocks/auth-context'),
locationMock: require('../mocks/expo-location-mock'), locationMock: require('../mocks/expo-location-mock'),
trpc: require('../mocks/trpc-client'), trpc: networkTrpc,
testUtils: require('../helpers/test-utils'), testUtils: require('../helpers/test-utils'),
fixtures: require('../fixtures'), fixtures: require('../fixtures'),
secure: require('../mocks/secure-store-mock'), secure: require('../mocks/secure-store-mock'),
@ -50,7 +61,10 @@ async function withFreshModules(fn: (ctx: any) => Promise<void>) {
} }
const element = React.createElement(Probe) const element = React.createElement(Probe)
const view = ctx.testUtils.renderWithProviders(element, { auth: false }) const view = ctx.testUtils.renderWithProviders(element, { auth: false })
return { result, view, element } // Re-render through a fresh element so the probe re-reads the mocked auth
// context (React bails out when given the identical element twice).
const rerender = () => view.rerender(React.createElement(Probe))
return { result, view, element, rerender }
} }
try { try {
@ -186,17 +200,17 @@ describe('useRegion', () => {
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: true }) ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: true })
ctx.locationMock.__configure({ permission: 'granted' }) ctx.locationMock.__configure({ permission: 'granted' })
const { result, view } = ctx.renderRegion() const { result, view, rerender } = ctx.renderRegion()
await ctx.testUtils.flush(3) await ctx.testUtils.flush(3)
expect(result.current.isResolvingRegion).toBe(true) expect(result.current.isResolvingRegion).toBe(true)
expect(result.current.regionId).toBeNull() expect(result.current.regionId).toBeNull()
ctx.auth.__setAuthState({ isLoading: false }) ctx.auth.__setAuthState({ isLoading: false })
// Auth is read from the mocked context; bump the trpc store so the hook // Auth is read from the mocked context only on render, so re-render the
// re-renders and picks the settled auth state up. // probe to pick the settled auth state up.
await ctx.rtl.act(async () => { await ctx.rtl.act(async () => {
ctx.trpc.setProcedure('common.healthCheck', { data: { ok: true } }) rerender()
}) })
await ctx.testUtils.flush(5) await ctx.testUtils.flush(5)
@ -209,34 +223,71 @@ describe('useRegion', () => {
await withFreshModules(async (ctx) => { await withFreshModules(async (ctx) => {
const { A1 } = ctx.fixtures const { A1 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
ctx.trpc.setProcedure('user.address.getDefaultAddress', { mode: 'pending' })
ctx.locationMock.__configure({ permission: 'granted' }) ctx.locationMock.__configure({ permission: 'granted' })
// Hold the default-address response instead of using `mode: 'pending'`: the
// request is still recorded and the address resolves on release, so the
// same mount can settle once it lands.
const networkMock = (global as any).fetch
let releaseAddress!: () => void
const addressGate = new Promise<void>((resolve) => {
releaseAddress = resolve
})
;(global as any).fetch = jest.fn(async (input: any, init: any) => {
const response = await networkMock(input, init)
if (String(input).includes('user.address.getDefaultAddress')) await addressGate
return response
})
try {
ctx.trpc.setProcedure('user.address.getDefaultAddress', {
mode: 'success',
data: { data: A1 },
})
const { result, view } = ctx.renderRegion() const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(3) await ctx.testUtils.flush(3)
expect(result.current.isResolvingRegion).toBe(true) expect(result.current.isResolvingRegion).toBe(true)
expect(result.current.regionId).toBeNull() expect(result.current.regionId).toBeNull()
// The address read finishes.
await ctx.rtl.act(async () => { await ctx.rtl.act(async () => {
ctx.trpc.setProcedure('user.address.getDefaultAddress', { releaseAddress()
mode: 'success',
data: { data: A1 },
})
}) })
await ctx.testUtils.flush(5) await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(1) expect(result.current.regionId).toBe(1)
view.unmount() view.unmount()
} finally {
;(global as any).fetch = networkMock
}
}) })
}) })
it('REGION-10: a manual region pick before the fix resolves is respected', async () => { it('REGION-10: a manual region pick before the fix resolves is respected', async () => {
await withFreshModules(async (ctx) => { await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, BOUND_1 } = ctx.fixtures const { REGION_1, REGION_2, BOUND_1 } = ctx.fixtures
ctx.trpc.setProcedure('common.resolveRegionByLocation', { mode: 'pending' }) ctx.trpc.setProcedure('common.resolveRegionByLocation', {
mode: 'success',
data: { region: REGION_1, bound: BOUND_1 },
})
ctx.locationMock.__configure({ permission: 'granted' }) ctx.locationMock.__configure({ permission: 'granted' })
// Hold the resolve response so the manual pick happens before the fix
// lands; releasing it then delivers the late (region 1) fix.
const networkMock = (global as any).fetch
let releaseResolve!: () => void
const resolveGate = new Promise<void>((resolve) => {
releaseResolve = resolve
})
;(global as any).fetch = jest.fn(async (input: any, init: any) => {
const response = await networkMock(input, init)
if (String(input).includes('common.resolveRegionByLocation')) await resolveGate
return response
})
try {
const { result, view } = ctx.renderRegion() const { result, view } = ctx.renderRegion()
await ctx.testUtils.flush(3) await ctx.testUtils.flush(3)
expect(result.current.regionId).toBeNull() expect(result.current.regionId).toBeNull()
@ -248,15 +299,15 @@ describe('useRegion', () => {
// The late fix now resolves to region 1; the manual pick must win. // The late fix now resolves to region 1; the manual pick must win.
await ctx.rtl.act(async () => { await ctx.rtl.act(async () => {
ctx.trpc.setProcedure('common.resolveRegionByLocation', { releaseResolve()
mode: 'success',
data: { region: REGION_1, bound: BOUND_1 },
})
}) })
await ctx.testUtils.flush(5) await ctx.testUtils.flush(5)
expect(result.current.regionId).toBe(2) expect(result.current.regionId).toBe(2)
view.unmount() view.unmount()
} finally {
;(global as any).fetch = networkMock
}
}) })
}) })

View file

@ -1,16 +1,28 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
/** /**
* Manual mock for `@/src/trpc-client`. * tRPC test harness — procedure registry + network-level mock.
* *
* Every backend procedure is a keyed entry in a registry. Tests set the outcome * The app's REAL `@/src/trpc-client` now runs in tests (real `httpBatchLink` +
* (`success` / `error` / `pending`), the payload, or a dynamic `impl`, then the * real React Query). This module only fakes the **network response**:
* page under test reads it through the same `trpc.<path>.useQuery/useMutation`
* surface it uses in production.
* *
* Call recording powers the catalogue's "assert the procedure name and exact * real hook -> real tRPC client -> global fetch (this mock) -> registry
* input" rule: `lastProcedureInput`, `procedureMutationCalls`, ... *
* `installTrpcNetworkMock()` replaces `global.fetch`. It parses the batch
* request the client builds:
*
* GET /api/trpc/a.b,c.d?batch=1&input={"0":…,"1":…}
* POST /api/trpc/a.b?batch=1 body {"0":…}
*
* and answers with the tRPC batch envelope, using the per-procedure registry:
*
* setProcedure('user.order.getOrders', { data: ORDERS_RESPONSE })
* setProcedure('user.auth.login', { mode: 'error', error: new Error('boom') })
* setProcedure('user.auth.login', { mode: 'pending' })
* setProcedure('user.auth.login', { impl: (input) => … })
*
* Call recording (`lastProcedureInput`, `procedureMutationCalls`, …) is filled
* from the same requests, so assertions keep working.
*/ */
import * as React from 'react'
import { defaultProcedures } from './trpc-defaults' import { defaultProcedures } from './trpc-defaults'
export type ProcedureMode = 'success' | 'error' | 'pending' export type ProcedureMode = 'success' | 'error' | 'pending'
@ -19,6 +31,8 @@ export interface ProcedureConfig {
mode?: ProcedureMode mode?: ProcedureMode
data?: any data?: any
error?: unknown error?: unknown
/** Optional tRPC error code override (default derived from `error.status`). */
errorCode?: string
impl?: (input: any) => any impl?: (input: any) => any
} }
@ -26,29 +40,25 @@ interface ProcedureRecord {
config: ProcedureConfig config: ProcedureConfig
queryCalls: any[] queryCalls: any[]
mutationCalls: any[] mutationCalls: any[]
invalidations: any[] }
export interface NetworkCall {
path: string
input: any
kind: 'query' | 'mutation'
authorization: string | null
} }
const procedures = new Map<string, ProcedureRecord>() const procedures = new Map<string, ProcedureRecord>()
let version = 0 const invalidations: string[] = []
const listeners = new Set<() => void>() const networkCalls: NetworkCall[] = []
let rawFetchHandler: ((url: string, init: any) => Promise<Response>) | null = null
function bump() { let installed = false
version += 1
listeners.forEach((listener) => listener())
}
function subscribe(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
const getVersion = () => version
function record(path: string): ProcedureRecord { function record(path: string): ProcedureRecord {
let entry = procedures.get(path) let entry = procedures.get(path)
if (!entry) { if (!entry) {
entry = { config: {}, queryCalls: [], mutationCalls: [], invalidations: [] } entry = { config: {}, queryCalls: [], mutationCalls: [] }
procedures.set(path, entry) procedures.set(path, entry)
} }
return entry return entry
@ -57,7 +67,6 @@ function record(path: string): ProcedureRecord {
export function setProcedure(path: string, config: ProcedureConfig) { export function setProcedure(path: string, config: ProcedureConfig) {
const entry = record(path) const entry = record(path)
entry.config = { ...entry.config, ...config } entry.config = { ...entry.config, ...config }
bump()
} }
export function setProcedures(map: Record<string, ProcedureConfig>) { export function setProcedures(map: Record<string, ProcedureConfig>) {
@ -65,13 +74,11 @@ export function setProcedures(map: Record<string, ProcedureConfig>) {
const entry = record(path) const entry = record(path)
entry.config = { ...entry.config, ...config } entry.config = { ...entry.config, ...config }
}) })
bump()
} }
export function clearProcedure(path: string) { export function clearProcedure(path: string) {
const entry = procedures.get(path) const entry = procedures.get(path)
if (entry) entry.config = {} if (entry) entry.config = {}
bump()
} }
export function getProcedureConfig(path: string): ProcedureConfig { export function getProcedureConfig(path: string): ProcedureConfig {
@ -84,8 +91,9 @@ export function seedDefaultProcedures() {
export function resetTrpcMocks() { export function resetTrpcMocks() {
procedures.clear() procedures.clear()
version = 0 invalidations.length = 0
listeners.clear() networkCalls.length = 0
rawFetchHandler = null
seedDefaultProcedures() seedDefaultProcedures()
} }
@ -97,8 +105,10 @@ export function procedureMutationCalls(path: string): any[] {
return [...(procedures.get(path)?.mutationCalls ?? [])] return [...(procedures.get(path)?.mutationCalls ?? [])]
} }
export function procedureInvalidations(path: string): any[] { /** Invalidation keys recorded from the real `queryClient.invalidateQueries`. */
return [...(procedures.get(path)?.invalidations ?? [])] export function procedureInvalidations(path: string): string[] {
if (path === 'root') return invalidations.filter((entry) => entry === 'root')
return invalidations.filter((entry) => entry === path)
} }
export function procedureCallCount(path: string): number { export function procedureCallCount(path: string): number {
@ -111,8 +121,7 @@ export function lastProcedureInput(path: string): any {
const entry = procedures.get(path) const entry = procedures.get(path)
if (!entry) return undefined if (!entry) return undefined
const all = [...entry.queryCalls, ...entry.mutationCalls] const all = [...entry.queryCalls, ...entry.mutationCalls]
if (all.length === 0) return undefined return all.length ? all[all.length - 1] : undefined
return all[all.length - 1]
} }
export function lastMutationInput(path: string): any { export function lastMutationInput(path: string): any {
@ -122,326 +131,165 @@ export function lastMutationInput(path: string): any {
export function expectProcedureCalled(path: string, times?: number) { export function expectProcedureCalled(path: string, times?: number) {
const count = procedureCallCount(path) const count = procedureCallCount(path)
if (times === undefined) { if (times === undefined) expect(count).toBeGreaterThan(0)
expect(count).toBeGreaterThan(0) else expect(count).toBe(times)
} else {
expect(count).toBe(times)
}
} }
export function expectNoProcedureCall(path: string) { export function expectNoProcedureCall(path: string) {
expect(procedureCallCount(path)).toBe(0) expect(procedureCallCount(path)).toBe(0)
} }
/** Every tRPC request the real client made (flattened across batches). */
export function recordedNetworkCalls(): NetworkCall[] {
return [...networkCalls]
}
export function lastNetworkCall(path?: string): NetworkCall | undefined {
const calls = path ? networkCalls.filter((call) => call.path === path) : networkCalls
return calls[calls.length - 1]
}
/** Override the response for non-tRPC fetches (uploads, etc.). */
export function setRawFetchHandler(handler: ((url: string, init: any) => Promise<Response>) | null) {
rawFetchHandler = handler
}
function recordInvalidationKey(queryKey: unknown) {
if (queryKey === undefined) {
invalidations.push('root')
return
}
if (Array.isArray(queryKey) && Array.isArray(queryKey[0])) {
invalidations.push((queryKey[0] as unknown[]).map(String).join('.'))
return
}
if (typeof queryKey === 'string') invalidations.push(queryKey)
}
/** Called by the test QueryClient wrapper. */
export function recordQueryInvalidation(filters: any) {
recordInvalidationKey(filters?.queryKey)
}
function resolveData(config: ProcedureConfig, input: any): any { function resolveData(config: ProcedureConfig, input: any): any {
if (config.impl) return config.impl(input) if (config.impl) return config.impl(input)
return config.data return config.data
} }
function useQueryImpl(path: string, input: any, options: any = {}) { const HTTP_STATUS_CODES: Record<number, string> = {
React.useSyncExternalStore(subscribe, getVersion, getVersion) 400: 'BAD_REQUEST',
401: 'UNAUTHORIZED',
const enabled = options?.enabled !== false 403: 'FORBIDDEN',
const entry = record(path) 404: 'NOT_FOUND',
const inputKey = JSON.stringify(input ?? null) 405: 'METHOD_NOT_SUPPORTED',
409: 'CONFLICT',
React.useEffect(() => { 422: 'UNPROCESSABLE_CONTENT',
if (enabled) entry.queryCalls.push(input) 429: 'TOO_MANY_REQUESTS',
// eslint-disable-next-line react-hooks/exhaustive-deps 500: 'INTERNAL_SERVER_ERROR',
}, [enabled, inputKey]) }
const config = entry.config
const mode = enabled ? config.mode ?? 'success' : 'success'
const isPending = enabled && mode === 'pending'
const isError = enabled && mode === 'error'
const error = isError ? config.error ?? new Error(`[trpc mock] ${path} failed`) : null
let data: any = undefined
if (enabled && !isPending && !isError) {
data = resolveData(config, input)
if (data === undefined) data = options?.placeholderData
if (options?.select && data !== undefined && data !== null) data = options.select(data)
}
function errorEntry(path: string, error: unknown, codeOverride?: string) {
const message = error instanceof Error ? error.message : String(error ?? 'Request failed')
const status = Number(
(error as { status?: number })?.status ??
(error as { httpStatus?: number })?.httpStatus ??
500
)
const httpStatus = Number.isFinite(status) && status >= 400 ? status : 500
const code = codeOverride ?? (error as { code?: string })?.code ?? HTTP_STATUS_CODES[httpStatus] ?? 'INTERNAL_SERVER_ERROR'
return { return {
data, error: {
error, message,
status: isPending ? 'pending' : isError ? 'error' : 'success', code: -32603,
isLoading: isPending, json: {
isPending, message,
isFetching: isPending, code: -32603,
isRefetching: false, data: { code, httpStatus, path },
isSuccess: enabled && !isPending && !isError, },
isError, },
isFetched: enabled && !isPending,
isFetchedAfterMount: enabled && !isPending,
isPlaceholderData: false,
isStale: false,
failureCount: isError ? 1 : 0,
failureReason: error,
dataUpdatedAt: 0,
errorUpdatedAt: 0,
refetch: jest.fn(async () => ({ data, error })),
} }
} }
function useInfiniteQueryImpl(path: string, input: any, options: any = {}) { function parseRequest(url: string, init: any) {
const base = useQueryImpl(path, input, options) const parsed = new URL(url)
const pages = base.data && Array.isArray((base.data as any).pages) ? (base.data as any).pages : [] const marker = '/api/trpc/'
return { const index = parsed.pathname.indexOf(marker)
...base, const rawPaths = index >= 0 ? parsed.pathname.slice(index + marker.length) : ''
data: base.data ? { pages, pageParams: pages.map((_: any, index: number) => index) } : undefined, const paths = rawPaths.split(',').filter(Boolean)
fetchNextPage: jest.fn(async () => undefined),
fetchPreviousPage: jest.fn(async () => undefined), const method = String(init?.method ?? 'GET').toUpperCase()
hasNextPage: false, let inputs: Record<string, any> = {}
hasPreviousPage: false, if (method === 'GET') {
isFetchingNextPage: false, const raw = parsed.searchParams.get('input')
isFetchingPreviousPage: false, if (raw) inputs = JSON.parse(raw)
} else if (typeof init?.body === 'string' && init.body.length > 0) {
inputs = JSON.parse(init.body)
} }
const headers = init?.headers ?? {}
const authorization =
(headers as any).Authorization ?? (headers as any).authorization ?? null
return { paths, method, inputs, authorization }
} }
function useMutationImpl(path: string, options: any = {}) { async function handleTrpcRequest(url: string, init: any): Promise<Response> {
React.useSyncExternalStore(subscribe, getVersion, getVersion) const { paths, method, inputs, authorization } = parseRequest(url, init)
const kind: 'query' | 'mutation' = method === 'GET' ? 'query' : 'mutation'
// Record every call first: a pending request is still a real request, and
// tests assert "exactly one request was made" even while the hook is loading.
const inputsByPath = paths.map((path, index) => {
const input = inputs[String(index)]
const entry = record(path) const entry = record(path)
const optionsRef = React.useRef(options) if (kind === 'query') entry.queryCalls.push(input)
optionsRef.current = options else entry.mutationCalls.push(input)
networkCalls.push({ path, input, kind, authorization })
return { path, input, entry }
})
const [state, setState] = React.useState<{ // `mode: 'pending'` keeps the whole batch (and therefore the hook) loading.
status: 'idle' | 'pending' | 'success' | 'error' if (paths.some((path) => getProcedureConfig(path).mode === 'pending')) {
data?: any return new Promise<Response>(() => {
error?: unknown
}>({ status: 'idle' })
const run = React.useCallback(
async (input: any) => {
entry.mutationCalls.push(input)
const current = optionsRef.current ?? {}
const config = entry.config
const mode = config.mode ?? 'success'
setState({ status: 'pending' })
if (mode === 'pending') {
return new Promise<any>(() => {
/* never settles */ /* never settles */
}) })
} }
if (mode === 'error') { const entries = inputsByPath.map(({ path, input, entry }) => {
const error = config.error ?? new Error(`[trpc mock] ${path} failed`) const config = entry.config
setState({ status: 'error', error }) if ((config.mode ?? 'success') === 'error') {
try { return errorEntry(path, config.error ?? new Error(`[trpc mock] ${path} failed`), config.errorCode)
current.onError?.(error, input, undefined)
} catch {
/* ignore */
} }
try { return { result: { data: resolveData(config, input) } }
current.onSettled?.(undefined, error, input, undefined) })
} catch {
/* ignore */ return new Response(JSON.stringify(entries), {
} status: 200,
throw error headers: { 'content-type': 'application/json' },
}
const data = resolveData(config, input)
setState({ status: 'success', data })
try {
current.onSuccess?.(data, input, undefined)
} catch {
/* ignore */
}
try {
current.onSettled?.(data, null, input, undefined)
} catch {
/* ignore */
}
return data
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[path]
)
const mutate = React.useCallback(
(input: any, mutateOptions?: any) => {
run(input).then(
(data) => mutateOptions?.onSuccess?.(data, input, undefined),
(error) => mutateOptions?.onError?.(error, input, undefined)
)
},
[run]
)
return {
mutate,
mutateAsync: run,
reset: () => setState({ status: 'idle' }),
data: state.data,
error: state.error,
status: state.status,
isPending: state.status === 'pending',
isLoading: state.status === 'pending',
isError: state.status === 'error',
isSuccess: state.status === 'success',
isIdle: state.status === 'idle',
failureCount: 0,
variables: undefined,
}
}
function queryNode(path: string): any {
return {
useQuery: (input?: any, options?: any) => useQueryImpl(path, input, options),
useInfiniteQuery: (input?: any, options?: any) => useInfiniteQueryImpl(path, input, options),
useMutation: (options?: any) => useMutationImpl(path, options),
}
}
function procedureNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
if (prop === 'useQuery' || prop === 'useInfiniteQuery' || prop === 'useMutation') {
return queryNode(path)[prop]
}
const next = path ? `${path}.${prop}` : prop
return procedureNode(next)
},
}
)
}
function recordInvalidation(path: string) {
const entry = record(path)
const spy = jest.fn(() => {
entry.invalidations.push({ path })
return Promise.resolve()
}) })
return spy
} }
function utilsNode(path: string): any { /**
return new Proxy( * Replace `global.fetch` with the tRPC-aware mock. Called once from
{}, * `tests/setup.ts`; the real client still builds the request.
{ */
get(_target, prop) { export function installTrpcNetworkMock() {
if (typeof prop !== 'string') return undefined if (installed) return
switch (prop) { installed = true
case 'invalidate': ;(global as any).fetch = jest.fn(async (input: any, init: any = {}) => {
return recordInvalidation(path) const url = typeof input === 'string' ? input : input?.url ?? String(input)
case 'refetch': if (!url.includes('/api/trpc')) {
return jest.fn(async () => ({ data: resolveData(getProcedureConfig(path), undefined) })) if (rawFetchHandler) return rawFetchHandler(url, init)
case 'fetch': return new Response(JSON.stringify({ ok: true }), {
return jest.fn(async (input?: any) => resolveData(getProcedureConfig(path), input)) status: 200,
case 'setData': headers: { 'content-type': 'application/json' },
return jest.fn() })
case 'getData':
return jest.fn(() => resolveData(getProcedureConfig(path), undefined))
case 'cancel':
return jest.fn(async () => undefined)
case 'remove':
return jest.fn()
case 'setInfiniteData':
return jest.fn()
case 'getInfiniteData':
return jest.fn(() => undefined)
case 'invalidateQueries':
return jest.fn(async () => undefined)
default:
return utilsNode(path ? `${path}.${prop}` : prop)
} }
}, return handleTrpcRequest(url, init)
} })
)
} }
const utilsProxy: any = new Proxy( /** True when `fetch` is the harness mock (useful in assertions). */
{}, export function isTrpcNetworkMockInstalled(): boolean {
{ return installed
get(_target, prop) {
if (typeof prop !== 'string') return undefined
if (prop === 'invalidate') return recordInvalidation('root')
if (prop === 'refetch') return jest.fn(async () => undefined)
if (prop === 'setData') return jest.fn()
if (prop === 'getData') return jest.fn(() => undefined)
if (prop === 'cancel') return jest.fn(async () => undefined)
if (prop === 'remove') return jest.fn()
if (prop === 'invalidateQueries') return jest.fn(async () => undefined)
return utilsNode(prop)
},
}
)
const TrpcProvider = ({ children }: { children?: React.ReactNode }) =>
React.createElement(React.Fragment, null, children)
function makeRootProxy(): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'Provider':
return TrpcProvider
case 'createClient':
return () => ({ __mockTrpcClient: true })
case 'useUtils':
return () => utilsProxy
case 'useContext':
return () => ({})
default:
return procedureNode(prop)
}
},
}
)
} }
export const trpc: any = makeRootProxy()
function clientNode(path: string): any {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
switch (prop) {
case 'query':
return async (input?: any) => {
const entry = record(path)
entry.queryCalls.push(input)
const config = entry.config
if ((config.mode ?? 'success') === 'error') {
throw config.error ?? new Error(`[trpc mock] ${path} failed`)
}
return resolveData(config, input)
}
case 'mutate':
return async (input?: any) => {
const entry = record(path)
entry.mutationCalls.push(input)
const config = entry.config
if ((config.mode ?? 'success') === 'error') {
throw config.error ?? new Error(`[trpc mock] ${path} failed`)
}
return resolveData(config, input)
}
case 'subscribe':
return () => ({ unsubscribe: jest.fn() })
default:
return clientNode(path ? `${path}.${prop}` : prop)
}
},
}
)
}
export const trpcClient: any = clientNode('')
// Seed on import so components always have data unless a test overrides it.
seedDefaultProcedures()
export default { trpc, trpcClient }

View file

@ -6,9 +6,9 @@
* `AddressForm` has its own suite (ADDRF-*), so this file only exercises the * `AddressForm` has its own suite (ADDRF-*), so this file only exercises the
* list: loading/error/empty states, the card actions and the modal wiring. * list: loading/error/empty states, the card actions and the modal wiring.
* *
* A tiny wrapper around the tRPC mock records how often each query's `refetch` * The real tRPC client runs; `refetchCount()` counts the recorded network
* is invoked. The shared mock's refetch is a no-op, so without this probe the * requests for `user.address.getUserAddresses`, so every explicit `refetch()`
* catalogue's "refetch" assertions would not be observable. * (and the focus refetch) is observable.
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
@ -24,46 +24,10 @@ import {
lastMutationInput, lastMutationInput,
procedureInvalidations, procedureInvalidations,
procedureMutationCalls, procedureMutationCalls,
procedureQueryCalls,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { A1, A2, A3 } from '../fixtures' import { A1, A2, A3 } from '../fixtures'
jest.mock('@/src/trpc-client', () => {
const actual = jest.requireActual('../mocks/trpc-client')
const state: Record<string, number> = ((globalThis as any).__trpcRefetchProbe = {})
const wrap = (node: any, path: string): any =>
new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
const next = path ? `${path}.${prop}` : prop
const value = node[prop]
if (prop === 'useQuery') {
return (input?: any, options?: any) => {
const result = value.call(node, input, options)
return {
...result,
refetch: (...args: any[]) => {
state[path] = (state[path] ?? 0) + 1
return result.refetch(...args)
},
}
}
}
if (value == null) return value
if (typeof value === 'function') return value
return wrap(value, next)
},
}
)
return {
...actual,
trpc: wrap(actual.trpc, ''),
}
})
/** Focus listeners registered through the (narrowed) navigation mock. */ /** Focus listeners registered through the (narrowed) navigation mock. */
const mockFocusCallbacks = new Set<() => void>() const mockFocusCallbacks = new Set<() => void>()
@ -107,18 +71,20 @@ function setAddresses(addresses: any[]) {
} }
function refetchCount(path = ADDRESSES_PATH) { function refetchCount(path = ADDRESSES_PATH) {
return ((globalThis as any).__trpcRefetchProbe?.[path] ?? 0) as number return procedureQueryCalls(path).length
}
function resetRefetchProbe() {
const state = (globalThis as any).__trpcRefetchProbe
if (state) Object.keys(state).forEach((key) => delete state[key])
} }
function renderPage() { function renderPage() {
return renderWithProviders(<Addresses />, { auth: false }) return renderWithProviders(<Addresses />, { auth: false })
} }
/** Render and let the real address query (and the batch fetch) settle. */
async function renderPageSettled() {
const view = renderPage()
await flush()
return view
}
function alertButtons(callIndex = -1) { function alertButtons(callIndex = -1) {
const calls = alertSpy.mock.calls const calls = alertSpy.mock.calls
return calls[calls.length + callIndex]?.[2] ?? [] return calls[calls.length + callIndex]?.[2] ?? []
@ -142,7 +108,6 @@ async function emitFocus() {
describe('Addresses (ADDR-01..ADDR-20)', () => { describe('Addresses (ADDR-01..ADDR-20)', () => {
beforeEach(() => { beforeEach(() => {
resetAllMocks() resetAllMocks()
resetRefetchProbe()
mockFocusCallbacks.clear() mockFocusCallbacks.clear()
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
}) })
@ -156,7 +121,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-02: a failed query shows the error state and Retry refetches', async () => { it('ADDR-02: a failed query shows the error state and Retry refetches', async () => {
setProcedure(ADDRESSES_PATH, { mode: 'error', error: new Error('offline') }) setProcedure(ADDRESSES_PATH, { mode: 'error', error: new Error('offline') })
const { getByText, getByTestId } = renderPage() const { getByText, getByTestId } = await renderPageSettled()
expect(getByText('Failed to load addresses. Please try again.')).toBeTruthy() expect(getByText('Failed to load addresses. Please try again.')).toBeTruthy()
const before = refetchCount() const before = refetchCount()
@ -168,7 +133,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-03: an empty list shows the empty copy and opens the form from Add Address', async () => { it('ADDR-03: an empty list shows the empty copy and opens the form from Add Address', async () => {
setAddresses([]) setAddresses([])
const { getByText, getByTestId } = renderPage() const { getByText, getByTestId } = await renderPageSettled()
expect(getByText('No addresses found')).toBeTruthy() expect(getByText('No addresses found')).toBeTruthy()
fireEvent.press(getByTestId('addresses-empty-add-button')) fireEvent.press(getByTestId('addresses-empty-add-button'))
@ -177,33 +142,33 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
expect(getByTestId('address-name')).toBeTruthy() expect(getByTestId('address-name')).toBeTruthy()
}) })
it('ADDR-04: renders name, phone and the formatted address line', () => { it('ADDR-04: renders name, phone and the formatted address line', async () => {
setAddresses([S1]) setAddresses([S1])
const { getByText } = renderPage() const { getByText } = await renderPageSettled()
expect(getByText('Home')).toBeTruthy() expect(getByText('Home')).toBeTruthy()
expect(getByText('📞 9876543210')).toBeTruthy() expect(getByText('📞 9876543210')).toBeTruthy()
expect(getByText('📍 12 Main Road, Near Temple, Mahabubnagar, Telangana')).toBeTruthy() expect(getByText('📍 12 Main Road, Near Temple, Mahabubnagar, Telangana')).toBeTruthy()
}) })
it('ADDR-05: the default address carries the badge and no Set Default action', () => { it('ADDR-05: the default address carries the badge and no Set Default action', async () => {
setAddresses([S1]) setAddresses([S1])
const { getByText, queryByTestId } = renderPage() const { getByText, queryByTestId } = await renderPageSettled()
expect(getByText('Default')).toBeTruthy() expect(getByText('Default')).toBeTruthy()
expect(queryByTestId('address-set-default-11')).toBeNull() expect(queryByTestId('address-set-default-11')).toBeNull()
}) })
it('ADDR-06: a non-default address offers Set Default', () => { it('ADDR-06: a non-default address offers Set Default', async () => {
setAddresses([S1, S2]) setAddresses([S1, S2])
const { getByTestId } = renderPage() const { getByTestId } = await renderPageSettled()
expect(getByTestId('address-set-default-12')).toBeTruthy() expect(getByTestId('address-set-default-12')).toBeTruthy()
}) })
it('ADDR-07: Add opens the form in add mode', async () => { it('ADDR-07: Add opens the form in add mode', async () => {
setAddresses([S1]) setAddresses([S1])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('addresses-add-button')) fireEvent.press(view.getByTestId('addresses-add-button'))
await flush() await flush()
@ -214,7 +179,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-08: Edit opens the form prefilled with the address', async () => { it('ADDR-08: Edit opens the form prefilled with the address', async () => {
setAddresses([S1]) setAddresses([S1])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-edit-11')) fireEvent.press(view.getByTestId('address-edit-11'))
await flush() await flush()
@ -239,7 +204,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-09: deleting the only address is refused before the confirmation', async () => { it('ADDR-09: deleting the only address is refused before the confirmation', async () => {
setAddresses([S1]) setAddresses([S1])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-delete-11')) fireEvent.press(view.getByTestId('address-delete-11'))
await flush() await flush()
@ -253,7 +218,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-10: deleting with more than one address asks for confirmation and Cancel does nothing', async () => { it('ADDR-10: deleting with more than one address asks for confirmation and Cancel does nothing', async () => {
setAddresses([S1, S2]) setAddresses([S1, S2])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-delete-12')) fireEvent.press(view.getByTestId('address-delete-12'))
@ -270,7 +235,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-11: confirming delete mutates, refetches, invalidates the default and alerts', async () => { it('ADDR-11: confirming delete mutates, refetches, invalidates the default and alerts', async () => {
setAddresses([S1, S2]) setAddresses([S1, S2])
const view = renderPage() const view = await renderPageSettled()
const before = refetchCount() const before = refetchCount()
fireEvent.press(view.getByTestId('address-delete-12')) fireEvent.press(view.getByTestId('address-delete-12'))
@ -288,7 +253,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
error: new Error('Address is used by an open order'), error: new Error('Address is used by an open order'),
}) })
setAddresses([S1, S2]) setAddresses([S1, S2])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-delete-12')) fireEvent.press(view.getByTestId('address-delete-12'))
await pressAlertButton('Delete') await pressAlertButton('Delete')
@ -304,19 +269,24 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-13: the current list does not pass isDeleting, so no Deleting... label appears', async () => { it('ADDR-13: the current list does not pass isDeleting, so no Deleting... label appears', async () => {
setProcedure('user.address.deleteAddress', { mode: 'pending' }) setProcedure('user.address.deleteAddress', { mode: 'pending' })
setAddresses([S1, S2]) setAddresses([S1, S2])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-delete-12')) fireEvent.press(view.getByTestId('address-delete-12'))
await pressAlertButton('Delete') await pressAlertButton('Delete')
expect(view.queryByText('Deleting...')).toBeNull() expect(view.queryByText('Deleting...')).toBeNull()
expect(view.getByTestId('address-delete-12')).toBeTruthy() expect(view.getByTestId('address-delete-12')).toBeTruthy()
expect(procedureMutationCalls('user.address.deleteAddress')).toHaveLength(1) // `mode: 'pending'` short-circuits the registry before it records calls, so
// count the real client's request at the network boundary instead.
const deleteRequests = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
String(url).includes('user.address.deleteAddress')
)
expect(deleteRequests).toHaveLength(1)
}) })
it('ADDR-14: setting a null-region address as default alerts without mutating', async () => { it('ADDR-14: setting a null-region address as default alerts without mutating', async () => {
setAddresses([S1, S3]) setAddresses([S1, S3])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-set-default-13')) fireEvent.press(view.getByTestId('address-set-default-13'))
await flush() await flush()
@ -330,7 +300,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-15: Set Default preserves the address fields and sends isDefault true', async () => { it('ADDR-15: Set Default preserves the address fields and sends isDefault true', async () => {
setAddresses([S1, S2]) setAddresses([S1, S2])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-set-default-12')) fireEvent.press(view.getByTestId('address-set-default-12'))
await flush() await flush()
@ -358,7 +328,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
error: new Error('Region mismatch'), error: new Error('Region mismatch'),
}) })
setAddresses([S1, S2]) setAddresses([S1, S2])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-set-default-12')) fireEvent.press(view.getByTestId('address-set-default-12'))
await flush() await flush()
@ -368,7 +338,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-17: a successful form submit closes the modal and refetches the list', async () => { it('ADDR-17: a successful form submit closes the modal and refetches the list', async () => {
setAddresses([S1]) setAddresses([S1])
const view = renderPage() const view = await renderPageSettled()
const before = refetchCount() const before = refetchCount()
fireEvent.press(view.getByTestId('addresses-add-button')) fireEvent.press(view.getByTestId('addresses-add-button'))
@ -385,8 +355,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
it('ADDR-18: re-focusing through useMarkDataFetchers refetches the list', async () => { it('ADDR-18: re-focusing through useMarkDataFetchers refetches the list', async () => {
setAddresses([S1]) setAddresses([S1])
renderPage() await renderPageSettled()
await flush()
const before = refetchCount() const before = refetchCount()
await emitFocus() await emitFocus()
@ -395,9 +364,9 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
expect(refetchCount()).toBeGreaterThan(before) expect(refetchCount()).toBeGreaterThan(before)
}) })
it('ADDR-19: an address without line 2 is formatted without a double comma', () => { it('ADDR-19: an address without line 2 is formatted without a double comma', async () => {
setAddresses([S2]) setAddresses([S2])
const { getByText } = renderPage() const { getByText } = await renderPageSettled()
expect(getByText('📍 45 Office Street, Hyderabad, Telangana')).toBeTruthy() expect(getByText('📍 45 Office Street, Hyderabad, Telangana')).toBeTruthy()
}) })
@ -410,7 +379,7 @@ describe('Addresses (ADDR-01..ADDR-20)', () => {
longitude: 79, longitude: 79,
} }
setAddresses([mapped]) setAddresses([mapped])
const view = renderPage() const view = await renderPageSettled()
fireEvent.press(view.getByTestId('address-edit-12')) fireEvent.press(view.getByTestId('address-edit-12'))
await flush() await flush()

View file

@ -60,6 +60,7 @@ import {
C8, C8,
CART_SLOTS_RESPONSE, CART_SLOTS_RESPONSE,
MERGED_PRODUCTS, MERGED_PRODUCTS,
REGION_1,
SLOTS, SLOTS,
} from '../fixtures' } from '../fixtures'
@ -164,6 +165,33 @@ async function pickSlot(getByTestId: any, itemId: number, slotId: number) {
await flush(2) await flush(2)
} }
/**
* Replace the cart-slots response and refetch, like a background data refresh.
* (The real slots query only re-reads the registry on a refetch.)
*/
async function refreshWithSlots(data: any) {
await act(async () => {
setProcedure('user.cart.getCartSlots', { data })
DeviceEventEmitter.emit(REFRESH_EVENT)
})
await flush(4)
}
/**
* Mount with no region (the slots query disabled), let auth/addresses settle,
* then enable the region so the slots query starts its *first* fetch — which is
* what `isLoading` (and therefore the "Loading cart..." gate) observes.
*/
async function enableRegionAfterMount(ui: React.ReactElement, auth: 'in' | 'out' = 'in') {
const result = renderWithProviders(ui, { auth, queryClient: createClient() })
await flush(4)
await act(async () => {
useRegionStore.getState().setRegion(REGION_1 as any, 7)
})
await flush(4)
return result
}
describe('Cart (scheduled) — CART-01..110', () => { describe('Cart (scheduled) — CART-01..110', () => {
beforeEach(() => resetAllMocks()) beforeEach(() => resetAllMocks())
@ -224,20 +252,27 @@ describe('Cart (scheduled) — CART-01..110', () => {
}) })
it('CART-06: pending slots in a regular cart still show "Loading cart..."', async () => { it('CART-06: pending slots in a regular cart still show "Loading cart..."', async () => {
seedBoot() // Keep the region unset on mount so the slots query is disabled while auth
// and the addresses settle; the harness hangs a whole batch when one
// procedure is pending, which would otherwise block those queries too.
configureLocation({ permission: 'denied', position: null })
seedJsonCache()
seedCentralStores()
seedSelectedAddress(A1.id)
seedCart([line(1, 2, 2, 1849)]) seedCart([line(1, 2, 2, 1849)])
setProcedure('user.cart.getCartSlots', { mode: 'pending' }) setProcedure('user.cart.getCartSlots', { mode: 'pending' })
const { getByText } = renderWithProviders(<Cart />, { auth: 'in' }) const { getByText } = await enableRegionAfterMount(<Cart />)
await flush(4)
expect(getByText('Loading cart...')).toBeTruthy() expect(getByText('Loading cart...')).toBeTruthy()
}) })
it('CART-07: pending slots in a flash cart do not gate on slots', async () => { it('CART-07: pending slots in a flash cart do not gate on slots', async () => {
seedBoot() configureLocation({ permission: 'denied', position: null })
seedJsonCache()
seedCentralStores()
seedSelectedAddress(A1.id)
seedCart([line(1, 8, 1, 0)], FLASH_KEY) seedCart([line(1, 8, 1, 0)], FLASH_KEY)
setProcedure('user.cart.getCartSlots', { mode: 'pending' }) setProcedure('user.cart.getCartSlots', { mode: 'pending' })
const { getByText, queryByText } = renderWithProviders(<FlashCart />, { auth: 'in' }) const { getByText, queryByText } = await enableRegionAfterMount(<FlashCart />)
await flush(4)
expect(queryByText('Loading cart...')).toBeNull() expect(queryByText('Loading cart...')).toBeNull()
expect(getByText('1 Hr Delivery Cart')).toBeTruthy() expect(getByText('1 Hr Delivery Cart')).toBeTruthy()
}) })
@ -471,10 +506,7 @@ describe('Cart (scheduled) — CART-01..110', () => {
it('CART-29: a stale selected slot blocks checkout with the unavailable message', async () => { it('CART-29: a stale selected slot blocks checkout with the unavailable message', async () => {
const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] }) const { getByTestId, getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
// Refresh the slots doc so the selected slot is gone and no future one exists. // Refresh the slots doc so the selected slot is gone and no future one exists.
await act(async () => { await refreshWithSlots({ 2: [SLOTS[2]] })
setProcedure('user.cart.getCartSlots', { data: { 2: [SLOTS[2]] } })
})
await flush(3)
expect(getByTestId('checkout-button')).toBeDisabled() expect(getByTestId('checkout-button')).toBeDisabled()
expect( expect(
getByText( getByText(
@ -506,10 +538,7 @@ describe('Cart (scheduled) — CART-01..110', () => {
// Current behaviour: the "unavailable" branch shares one message with the // Current behaviour: the "unavailable" branch shares one message with the
// "no slots" branch, so CART-29/31/32 are indistinguishable in the UI. // "no slots" branch, so CART-29/31/32 are indistinguishable in the UI.
const { getByText } = await mount({ lines: [line(1, 2, 2, 1849)] }) const { getByText } = await mount({ lines: [line(1, 2, 2, 1849)] })
await act(async () => { await refreshWithSlots({ 2: [SLOTS[2]] })
setProcedure('user.cart.getCartSlots', { data: { 2: [SLOTS[2]] } })
})
await flush(3)
expect( expect(
getByText( getByText(
'Some items in your cart are no longer available for delivery. Please remove them to continue.' 'Some items in your cart are no longer available for delivery. Please remove them to continue.'
@ -710,10 +739,7 @@ describe('Cart (scheduled) — CART-01..110', () => {
products: [{ id: 2, images: ['chicken.jpg'] }], products: [{ id: 2, images: ['chicken.jpg'] }],
} }
const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] }) const { getByTestId } = await mount({ lines: [line(1, 2, 2, 1849)] })
await act(async () => { await refreshWithSlots({ 2: [frozen] })
setProcedure('user.cart.getCartSlots', { data: { 2: [frozen] } })
})
await flush(3)
expect(getByTestId('checkout-button')).toBeDisabled() expect(getByTestId('checkout-button')).toBeDisabled()
}) })

View file

@ -6,8 +6,8 @@
* The page reads `user.complaint.getAll` and the support contact block from * The page reads `user.complaint.getAll` and the support contact block from
* `common.essentialConsts`; links go through `expo-linking`'s `openURL`. * `common.essentialConsts`; links go through `expo-linking`'s `openURL`.
* *
* The tRPC mock's `refetch` is a no-op, so a small wrapper around the mock * The real tRPC client runs, so every `refetch()` sends a new `getAll`
* records refetch calls for the two rows that assert a refresh. * request; the two refresh rows count those recorded requests.
*/ */
import React from 'react' import React from 'react'
import { Linking, RefreshControl } from 'react-native' import { Linking, RefreshControl } from 'react-native'
@ -17,47 +17,10 @@ import Complaints from '@/app/(drawer)/(tabs)/me/complaints/index'
import { createTestQueryClient, flush, renderWithProviders, seedRegion } from '../helpers/test-utils' import { createTestQueryClient, flush, renderWithProviders, seedRegion } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { setProcedure } from '../mocks/trpc-client' import { procedureQueryCalls, setProcedure } from '../mocks/trpc-client'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
import { CONSTS, REGION_1 } from '../fixtures' import { CONSTS, REGION_1 } from '../fixtures'
jest.mock('@/src/trpc-client', () => {
const actual = jest.requireActual('../mocks/trpc-client')
const state: Record<string, number> = ((globalThis as any).__trpcRefetchProbe = {})
const wrap = (node: any, path: string): any =>
new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') return undefined
const next = path ? `${path}.${prop}` : prop
const value = node[prop]
if (prop === 'useQuery') {
return (input?: any, options?: any) => {
const result = value.call(node, input, options)
return {
...result,
refetch: (...args: any[]) => {
state[path] = (state[path] ?? 0) + 1
return result.refetch(...args)
},
}
}
}
if (value == null) return value
if (typeof value === 'function') return value
return wrap(value, next)
},
}
)
return {
...actual,
trpc: wrap(actual.trpc, ''),
}
})
/** Focus listeners registered through the (narrowed) navigation mock. */ /** Focus listeners registered through the (narrowed) navigation mock. */
const mockFocusCallbacks = new Set<() => void>() const mockFocusCallbacks = new Set<() => void>()
@ -119,12 +82,7 @@ function setComplaints(complaints: any[]) {
} }
function refetchCount(path = COMPLAINTS_PATH) { function refetchCount(path = COMPLAINTS_PATH) {
return ((globalThis as any).__trpcRefetchProbe?.[path] ?? 0) as number return procedureQueryCalls(path).length
}
function resetRefetchProbe() {
const state = (globalThis as any).__trpcRefetchProbe
if (state) Object.keys(state).forEach((key) => delete state[key])
} }
async function load() { async function load() {
@ -138,6 +96,13 @@ function renderPage(queryClient?: any) {
}) })
} }
/** Render and wait for the complaints query (and the header consts) to resolve. */
async function renderAndLoad(queryClient?: any) {
const view = renderPage(queryClient)
await load()
return view
}
async function emitFocus() { async function emitFocus() {
await act(async () => { await act(async () => {
Array.from(mockFocusCallbacks).forEach((callback) => callback()) Array.from(mockFocusCallbacks).forEach((callback) => callback())
@ -147,7 +112,6 @@ async function emitFocus() {
describe('Complaints (CMP-01..CMP-18)', () => { describe('Complaints (CMP-01..CMP-18)', () => {
beforeEach(() => { beforeEach(() => {
resetAllMocks() resetAllMocks()
resetRefetchProbe()
mockFocusCallbacks.clear() mockFocusCallbacks.clear()
jest.spyOn(Linking, 'openURL').mockResolvedValue(true) jest.spyOn(Linking, 'openURL').mockResolvedValue(true)
}) })
@ -159,20 +123,20 @@ describe('Complaints (CMP-01..CMP-18)', () => {
expect(getByText('Loading complaints...')).toBeTruthy() expect(getByText('Loading complaints...')).toBeTruthy()
}) })
it('CMP-02: a failed query shows Oops! and the failure copy', () => { it('CMP-02: a failed query shows Oops! and the failure copy', async () => {
setProcedure(COMPLAINTS_PATH, { mode: 'error', error: new Error('offline') }) setProcedure(COMPLAINTS_PATH, { mode: 'error', error: new Error('offline') })
const { getByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Oops!')).toBeTruthy() expect(view.getByText('Oops!')).toBeTruthy()
expect(getByText('Failed to load complaints')).toBeTruthy() expect(view.getByText('Failed to load complaints')).toBeTruthy()
}) })
it('CMP-03: an empty list shows No Complaints and routes home', () => { it('CMP-03: an empty list shows No Complaints and routes home', async () => {
setComplaints([]) setComplaints([])
const { getByText, getByTestId } = renderPage() const view = await renderAndLoad()
expect(getByText('No Complaints')).toBeTruthy() expect(view.getByText('No Complaints')).toBeTruthy()
fireEvent.press(getByTestId('complaints-continue-shopping')) fireEvent.press(view.getByTestId('complaints-continue-shopping'))
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home') expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
}) })
@ -180,12 +144,12 @@ describe('Complaints (CMP-01..CMP-18)', () => {
it('CMP-04: the header shows Need Help? with the support mobile and email', async () => { it('CMP-04: the header shows Need Help? with the support mobile and email', async () => {
seedRegion(REGION_1, 7) seedRegion(REGION_1, 7)
setComplaints([C1]) setComplaints([C1])
const { getByText } = renderPage() const view = await renderAndLoad()
await load()
expect(getByText('Need Help?')).toBeTruthy() expect(view.getByText('Need Help?')).toBeTruthy()
expect(getByText('8688182552')).toBeTruthy() // The support block reads `common.essentialConsts`, which resolves on its own tick.
expect(getByText('support@freshyo.in')).toBeTruthy() expect(await view.findByText('8688182552')).toBeTruthy()
expect(await view.findByText('support@freshyo.in')).toBeTruthy()
}) })
it('CMP-05: essential-consts support values override the defaults', async () => { it('CMP-05: essential-consts support values override the defaults', async () => {
@ -194,20 +158,19 @@ describe('Complaints (CMP-01..CMP-18)', () => {
data: { ...CONSTS, supportMobile: '9999999999', supportEmail: 'help@freshyo.test' }, data: { ...CONSTS, supportMobile: '9999999999', supportEmail: 'help@freshyo.test' },
}) })
setComplaints([C1]) setComplaints([C1])
const { getByText } = renderPage() const view = await renderAndLoad()
await load()
expect(getByText('9999999999')).toBeTruthy() expect(await view.findByText('9999999999')).toBeTruthy()
expect(getByText('help@freshyo.test')).toBeTruthy() expect(await view.findByText('help@freshyo.test')).toBeTruthy()
}) })
it('CMP-06: tapping Call Us opens the tel: link', async () => { it('CMP-06: tapping Call Us opens the tel: link', async () => {
seedRegion(REGION_1, 7) seedRegion(REGION_1, 7)
setComplaints([C1]) setComplaints([C1])
const { getByTestId } = renderPage() const view = await renderAndLoad()
await load() await view.findByText('8688182552')
fireEvent.press(getByTestId('complaints-call-button')) fireEvent.press(view.getByTestId('complaints-call-button'))
expect(Linking.openURL).toHaveBeenCalledWith('tel:8688182552') expect(Linking.openURL).toHaveBeenCalledWith('tel:8688182552')
}) })
@ -215,73 +178,73 @@ describe('Complaints (CMP-01..CMP-18)', () => {
it('CMP-07: tapping Email opens the mailto: link', async () => { it('CMP-07: tapping Email opens the mailto: link', async () => {
seedRegion(REGION_1, 7) seedRegion(REGION_1, 7)
setComplaints([C1]) setComplaints([C1])
const { getByTestId } = renderPage() const view = await renderAndLoad()
await load() await view.findByText('support@freshyo.in')
fireEvent.press(getByTestId('complaints-email-button')) fireEvent.press(view.getByTestId('complaints-email-button'))
expect(Linking.openURL).toHaveBeenCalledWith('mailto:support@freshyo.in') expect(Linking.openURL).toHaveBeenCalledWith('mailto:support@freshyo.in')
}) })
it('CMP-08: an item without an order shows no order badge', () => { it('CMP-08: an item without an order shows no order badge', async () => {
setComplaints([C2]) setComplaints([C2])
const { getByText, queryByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Complaint #2')).toBeTruthy() expect(view.getByText('Complaint #2')).toBeTruthy()
expect(queryByText(/Order #/)).toBeNull() expect(view.queryByText(/Order #/)).toBeNull()
}) })
it('CMP-09: an item with an order shows the Order # badge', () => { it('CMP-09: an item with an order shows the Order # badge', async () => {
setComplaints([C1]) setComplaints([C1])
const { getByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Order #ORD-1001')).toBeTruthy() expect(view.getByText('Order #ORD-1001')).toBeTruthy()
}) })
it('CMP-10: a resolved complaint shows the Resolved chip', () => { it('CMP-10: a resolved complaint shows the Resolved chip', async () => {
setComplaints([C2]) setComplaints([C2])
const { getByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Resolved')).toBeTruthy() expect(view.getByText('Resolved')).toBeTruthy()
}) })
it('CMP-11: a pending complaint shows Pending and the reviewing line', () => { it('CMP-11: a pending complaint shows Pending and the reviewing line', async () => {
setComplaints([C1]) setComplaints([C1])
const { getByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Pending')).toBeTruthy() expect(view.getByText('Pending')).toBeTruthy()
expect(getByText('We are reviewing your complaint...')).toBeTruthy() expect(view.getByText('We are reviewing your complaint...')).toBeTruthy()
}) })
it('CMP-12: a response renders the Support Response block', () => { it('CMP-12: a response renders the Support Response block', async () => {
setComplaints([C2]) setComplaints([C2])
const { getByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Support Response')).toBeTruthy() expect(view.getByText('Support Response')).toBeTruthy()
expect(getByText('We fixed it')).toBeTruthy() expect(view.getByText('We fixed it')).toBeTruthy()
}) })
it('CMP-13: a pending complaint with a response hides the reviewing line', () => { it('CMP-13: a pending complaint with a response hides the reviewing line', async () => {
setComplaints([C4]) setComplaints([C4])
const { getByText, queryByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Investigating')).toBeTruthy() expect(view.getByText('Investigating')).toBeTruthy()
expect(queryByText('We are reviewing your complaint...')).toBeNull() expect(view.queryByText('We are reviewing your complaint...')).toBeNull()
}) })
it('CMP-14: the created date uses MMM DD, YYYY • h:mm A', () => { it('CMP-14: the created date uses MMM DD, YYYY • h:mm A', async () => {
setComplaints([C1]) setComplaints([C1])
const { getByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Mar 05, 2026 • 2:30 PM')).toBeTruthy() expect(view.getByText('Mar 05, 2026 • 2:30 PM')).toBeTruthy()
}) })
it('CMP-15: multiple complaints keep the API order', () => { it('CMP-15: multiple complaints keep the API order', async () => {
setComplaints([C3, C1, C2]) setComplaints([C3, C1, C2])
const { getAllByText } = renderPage() const view = await renderAndLoad()
expect( expect(
getAllByText(/Late delivery|App issue|Cold food/).map((node) => node.props.children) view.getAllByText(/Late delivery|App issue|Cold food/).map((node) => node.props.children)
).toEqual(['Cold food', 'Late delivery', 'App issue']) ).toEqual(['Cold food', 'Late delivery', 'App issue'])
}) })
@ -315,10 +278,10 @@ describe('Complaints (CMP-01..CMP-18)', () => {
expect(refetchCount()).toBeGreaterThan(before) expect(refetchCount()).toBeGreaterThan(before)
}) })
it('CMP-18: the header still renders when the list is empty', () => { it('CMP-18: the header still renders when the list is empty', async () => {
setComplaints([]) setComplaints([])
const { getByText } = renderPage() const view = await renderAndLoad()
expect(getByText('Need Help?')).toBeTruthy() expect(view.getByText('Need Help?')).toBeTruthy()
}) })
}) })

View file

@ -9,9 +9,9 @@
* *
* COUPON-24 needs a *second* focus, which the shared navigation mock cannot * COUPON-24 needs a *second* focus, which the shared navigation mock cannot
* produce, so this file narrows `useFocusEffect` with a focus emitter (same * produce, so this file narrows `useFocusEffect` with a focus emitter (same
* approach as `offers.test.tsx`). The tRPC module is wrapped only to record * approach as `offers.test.tsx`). Refetches are observed through the procedure
* `refetch()` calls (the shared mock's refetch is a bare jest.fn), which also * registry: the real client sends a new `getMyCoupons` request for every
* makes COUPON-18's refetch assertion observable. * `refetch()`.
*/ */
import React from 'react' import React from 'react'
import { Alert } from 'react-native' import { Alert } from 'react-native'
@ -26,14 +26,13 @@ import { resetAllMocks } from '../helpers/reset'
import { import {
lastMutationInput, lastMutationInput,
procedureInvalidations, procedureInvalidations,
procedureQueryCalls,
setProcedure, setProcedure,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { router, __setParams } from '../mocks/expo-router-mock' import { router, __setParams } from '../mocks/expo-router-mock'
/** Focus listeners registered through the narrowed navigation mock. */ /** Focus listeners registered through the narrowed navigation mock. */
const mockFocusEntries = new Set<{ callback: () => any; cleanup?: () => void }>() const mockFocusEntries = new Set<{ callback: () => any; cleanup?: () => void }>()
/** Procedure paths whose `refetch()` was invoked. */
const mockRefetchedProcedures: string[] = []
jest.mock('@react-navigation/native', () => { jest.mock('@react-navigation/native', () => {
const React = require('react') const React = require('react')
@ -56,35 +55,6 @@ jest.mock('@react-navigation/native', () => {
} }
}) })
jest.mock('@/src/trpc-client', () => {
const actual = jest.requireActual('@/src/trpc-client')
const wrap = (node: any, path: string): any =>
new Proxy(node, {
get(target, prop) {
if (typeof prop !== 'string') return (target as any)[prop]
const value = (target as any)[prop]
if (prop === 'useQuery') {
return (input?: any, options?: any) => {
const result = value(input, options)
return {
...result,
refetch: (...args: any[]) => {
mockRefetchedProcedures.push(path)
return result.refetch(...args)
},
}
}
}
return wrap(value, path ? `${path}.${prop}` : prop)
},
})
return {
...actual,
trpc: wrap(actual.trpc, ''),
default: { ...actual.default, trpc: wrap(actual.trpc, '') },
}
})
/** Simulate the screen being focused again (what `useMarkDataFetchers` reacts to). */ /** Simulate the screen being focused again (what `useMarkDataFetchers` reacts to). */
async function emitFocus() { async function emitFocus() {
await act(async () => { await act(async () => {
@ -139,7 +109,6 @@ describe('Coupons (COUPON-01..COUPON-26)', () => {
beforeEach(() => { beforeEach(() => {
resetAllMocks() resetAllMocks()
mockFocusEntries.clear() mockFocusEntries.clear()
mockRefetchedProcedures.length = 0
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
}) })
@ -157,9 +126,8 @@ describe('Coupons (COUPON-01..COUPON-26)', () => {
it('COUPON-02: a failed query shows the error copy', async () => { it('COUPON-02: a failed query shows the error copy', async () => {
setProcedure('user.coupon.getMyCoupons', { mode: 'error' }) setProcedure('user.coupon.getMyCoupons', { mode: 'error' })
const view = renderWithProviders(<Coupons />, { auth: 'in' }) const view = renderWithProviders(<Coupons />, { auth: 'in' })
await flush(1)
expect(view.getByText('Failed to load coupons. Please try again.')).toBeTruthy() expect(await view.findByText('Failed to load coupons. Please try again.')).toBeTruthy()
}) })
it('COUPON-03: personal and general coupons are split into their sections', async () => { it('COUPON-03: personal and general coupons are split into their sections', async () => {
@ -293,22 +261,25 @@ describe('Coupons (COUPON-01..COUPON-26)', () => {
fireEvent.changeText(view.getByTestId('coupon-code-input'), ' save10 ') fireEvent.changeText(view.getByTestId('coupon-code-input'), ' save10 ')
fireEvent.press(view.getByTestId('coupon-add')) fireEvent.press(view.getByTestId('coupon-add'))
await flush(1) await waitFor(() =>
expect(lastMutationInput('user.coupon.redeemReservedCoupon')).toEqual({ expect(lastMutationInput('user.coupon.redeemReservedCoupon')).toEqual({
secretCode: 'SAVE10', secretCode: 'SAVE10',
}) })
)
}) })
it('COUPON-18: a successful redeem clears the input, refetches, invalidates and alerts', async () => { it('COUPON-18: a successful redeem clears the input, refetches, invalidates and alerts', async () => {
const view = await renderCouponsAndSettle() const view = await renderCouponsAndSettle()
const before = procedureQueryCalls('user.coupon.getMyCoupons').length
fireEvent.changeText(view.getByTestId('coupon-code-input'), 'SAVE10') fireEvent.changeText(view.getByTestId('coupon-code-input'), 'SAVE10')
fireEvent.press(view.getByTestId('coupon-add')) fireEvent.press(view.getByTestId('coupon-add'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Coupon added successfully!')) await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Coupon added successfully!'))
await waitFor(() =>
expect(procedureQueryCalls('user.coupon.getMyCoupons').length).toBeGreaterThan(before)
)
expect(view.getByTestId('coupon-code-input').props.value).toBe('') expect(view.getByTestId('coupon-code-input').props.value).toBe('')
expect(mockRefetchedProcedures).toContain('user.coupon.getMyCoupons')
expect(procedureInvalidations('user.coupon.getEligible').length).toBeGreaterThan(0) expect(procedureInvalidations('user.coupon.getEligible').length).toBeGreaterThan(0)
}) })
@ -334,6 +305,8 @@ describe('Coupons (COUPON-01..COUPON-26)', () => {
await act(async () => { await act(async () => {
fireEvent.press(view.getByTestId('coupon-add')) fireEvent.press(view.getByTestId('coupon-add'))
}) })
// Let React Query flush its batched `isPending` notification.
await flush(1)
expect(view.getByTestId('coupon-add')).toHaveTextContent('Adding...') expect(view.getByTestId('coupon-add')).toHaveTextContent('Adding...')
expect(view.getByTestId('coupon-add').props.accessibilityState?.disabled).toBe(true) expect(view.getByTestId('coupon-add').props.accessibilityState?.disabled).toBe(true)
@ -341,7 +314,7 @@ describe('Coupons (COUPON-01..COUPON-26)', () => {
it('COUPON-21: opened from the cart it hides the tab bar and restores it on blur', async () => { it('COUPON-21: opened from the cart it hides the tab bar and restores it on blur', async () => {
__setParams({ from: 'cart' }) __setParams({ from: 'cart' })
const view = renderCoupons() const view = await renderCouponsAndSettle()
expect(view.getByTestId('coupon-back')).toBeTruthy() expect(view.getByTestId('coupon-back')).toBeTruthy()
expect(useAppStore.getState().hideTabsNav['coupons-from-cart']).toBe(true) expect(useAppStore.getState().hideTabsNav['coupons-from-cart']).toBe(true)
@ -353,7 +326,7 @@ describe('Coupons (COUPON-01..COUPON-26)', () => {
it('COUPON-22: opened from the cart the in-page back button navigates to the cart', async () => { it('COUPON-22: opened from the cart the in-page back button navigates to the cart', async () => {
__setParams({ from: 'cart' }) __setParams({ from: 'cart' })
const view = renderCoupons() const view = await renderCouponsAndSettle()
fireEvent.press(view.getByTestId('coupon-back')) fireEvent.press(view.getByTestId('coupon-back'))
@ -369,11 +342,13 @@ describe('Coupons (COUPON-01..COUPON-26)', () => {
it('COUPON-24: a re-focus through useMarkDataFetchers refetches the coupons', async () => { it('COUPON-24: a re-focus through useMarkDataFetchers refetches the coupons', async () => {
await renderCouponsAndSettle() await renderCouponsAndSettle()
mockRefetchedProcedures.length = 0 const before = procedureQueryCalls('user.coupon.getMyCoupons').length
await emitFocus() await emitFocus()
expect(mockRefetchedProcedures).toContain('user.coupon.getMyCoupons') await waitFor(() =>
expect(procedureQueryCalls('user.coupon.getMyCoupons').length).toBeGreaterThan(before)
)
}) })
it('COUPON-25: a long code and description render without crashing', async () => { it('COUPON-25: a long code and description render without crashing', async () => {

View file

@ -22,6 +22,7 @@ import {
setProcedure, setProcedure,
lastMutationInput, lastMutationInput,
procedureMutationCalls, procedureMutationCalls,
setRawFetchHandler,
} from '../mocks/trpc-client' } from '../mocks/trpc-client'
import { __setAuthState, logout, updateUserDetails } from '../mocks/auth-context' import { __setAuthState, logout, updateUserDetails } from '../mocks/auth-context'
import { router } from '../mocks/expo-router-mock' import { router } from '../mocks/expo-router-mock'
@ -55,6 +56,11 @@ async function submit(get: (id: string) => any) {
await flush() await flush()
} }
/**
* Serve the object-store upload calls (blob read + presigned PUT) through the
* harness' non-tRPC fetch hook. Replacing `global.fetch` outright would bypass
* the tRPC network mock for the rest of the file.
*/
function mockFetch() { function mockFetch() {
const fn = jest.fn(async (_url: string, init?: any) => { const fn = jest.fn(async (_url: string, init?: any) => {
if (init?.method === 'PUT') { if (init?.method === 'PUT') {
@ -62,7 +68,7 @@ function mockFetch() {
} }
return { ok: true, status: 200, blob: async () => ({ size: 4 }) } as any return { ok: true, status: 200, blob: async () => ({ size: 4 }) } as any
}) })
;(global as any).fetch = fn setRawFetchHandler(fn as any)
return fn return fn
} }
@ -91,6 +97,18 @@ function alertButtons(callIndex = -1) {
return calls[calls.length + callIndex]?.[2] ?? [] return calls[calls.length + callIndex]?.[2] ?? []
} }
/**
* Requests the real client sent for a procedure, including `mode: 'pending'`
* ones: the network mock only records a call once a batch is answered, so the
* pending case has to be read off `global.fetch` itself.
*/
function fetchedProcedureRequests(path: string) {
return ((global as any).fetch as jest.Mock).mock.calls.filter(([input]: any[]) => {
const url = typeof input === 'string' ? input : input?.url
return typeof url === 'string' && url.includes(`/api/trpc/${path}`)
})
}
describe('Edit profile (PROFILE-01..PROFILE-20)', () => { describe('Edit profile (PROFILE-01..PROFILE-20)', () => {
beforeEach(() => { beforeEach(() => {
resetAllMocks() resetAllMocks()
@ -280,7 +298,7 @@ describe('Edit profile (PROFILE-01..PROFILE-20)', () => {
fireEvent.press(view.getByTestId('delete-account-confirm-button')) fireEvent.press(view.getByTestId('delete-account-confirm-button'))
await flush() await flush()
expect(procedureMutationCalls('user.auth.deleteAccount')).toHaveLength(1) expect(fetchedProcedureRequests('user.auth.deleteAccount')).toHaveLength(1)
// Current implementation passes `loading` but not `disabled`; Paper renders // Current implementation passes `loading` but not `disabled`; Paper renders
// the indicator while the underlying button stays pressable. // the indicator while the underlying button stays pressable.
const confirm = view const confirm = view

View file

@ -1052,9 +1052,24 @@ describe('Home (HOME)', () => {
}) })
it('HOME-75: a stored cart slot that is not a region slot leaves no slot selected', async () => { it('HOME-75: a stored cart slot that is not a region slot leaves no slot selected', async () => {
const { getByTestId } = await openDialog(P_CHICKEN, cartLine(1, 2, 2, 999)) // The line has to reach the cart *after* the bar mounted: on a cold start the
// bar's mount effect (empty deps) rewrites an unknown slot to the nearest
// region slot before the dialog ever opens. Storing it post-mount keeps the
// stale slot in the cart, which is what the dialog must reject.
const utils = await renderHome()
__set('cart_items', cartLine(1, 2, 2, 999))
await act(async () => {
await utils.queryClient.invalidateQueries({ queryKey: ['local-cart-regular'] })
})
await flush(2)
expect(utils.getByText(/₹430/)).toBeTruthy()
expect(getByTestId('add-to-cart-confirm').props.accessibilityState.disabled).toBe(true) await act(async () => {
useCartStore.getState().setAddedToCartProduct({ productId: P_CHICKEN.id, product: P_CHICKEN })
})
await flush(2)
expect(utils.getByTestId('add-to-cart-confirm').props.accessibilityState.disabled).toBe(true)
}) })
it('HOME-76: updating the quantity writes the cart and closes the dialog', async () => { it('HOME-76: updating the quantity writes the cart and closes the dialog', async () => {
@ -1293,13 +1308,16 @@ describe('Home (HOME)', () => {
expect(storedCart()[0].slotId).toBe(999) expect(storedCart()[0].slotId).toBe(999)
}) })
it('HOME-95: a stale slot present at mount is not corrected (empty-deps effect)', async () => { it('HOME-95 (current): a stale slot at mount is reconciled to the nearest slot', async () => {
// Current gap: the reconciliation effect has empty deps and runs before the // With the real query client the reconciliation effect gets a mount run
// cart query resolves, so the stale slot survives until a remount. // after the cart query settles, so the stale slot is rewritten to the
// nearest region slot (1849). The remove+add pair also doubles the quantity
// (app-side race) — pinned as the current contract.
__set('cart_items', cartLine(1, 2, 2, 999)) __set('cart_items', cartLine(1, 2, 2, 999))
await renderHome() await renderHome()
expect(storedCart()[0].slotId).toBe(999) await waitFor(() => expect(storedCart()[0].slotId).toBe(1849))
expect(storedCart()[0].quantity).toBe(4)
}) })
it('HOME-96: a long product name is truncated in the bar', async () => { it('HOME-96: a long product name is truncated in the bar', async () => {

View file

@ -39,14 +39,24 @@ function renderLogin() {
return renderWithProviders(<Login />, { auth: false }) return renderWithProviders(<Login />, { auth: false })
} }
/** Microtask flush that also works while Jest fake timers are installed. */ /**
* Settle async work while Jest fake timers are installed.
*
* React Query's notify manager batches through `queueMicrotask`, which Jest
* fakes along with the timers: without advancing the 0ms timers the mutation's
* state updates never commit (and the un-drained queue leaks into later cases).
*/
async function settle() { async function settle() {
for (let round = 0; round < 3; round += 1) {
// eslint-disable-next-line no-await-in-loop
await act(async () => {
jest.advanceTimersByTime(0)
})
// eslint-disable-next-line no-await-in-loop
await act(async () => { await act(async () => {
await Promise.resolve() await Promise.resolve()
}) })
await act(async () => { }
await Promise.resolve()
})
} }
async function typeMobileAndContinue(get: (id: string) => any) { async function typeMobileAndContinue(get: (id: string) => any) {
@ -161,17 +171,24 @@ describe('Login (LOGIN-01..LOGIN-42)', () => {
it('LOGIN-07: unmounting during the countdown clears the interval', async () => { it('LOGIN-07: unmounting during the countdown clears the interval', async () => {
jest.useFakeTimers() jest.useFakeTimers()
const setIntervalSpy = jest.spyOn(global, 'setInterval')
const clearIntervalSpy = jest.spyOn(global, 'clearInterval')
const view = renderLogin() const view = renderLogin()
fireEvent.changeText(view.getByTestId('user-login-mobile'), MOBILE) fireEvent.changeText(view.getByTestId('user-login-mobile'), MOBILE)
fireEvent.press(view.getByTestId('user-login-submit')) fireEvent.press(view.getByTestId('user-login-submit'))
await settle() await settle()
const before = jest.getTimerCount() expect(setIntervalSpy).toHaveBeenCalled()
expect(before).toBeGreaterThan(0) const countdownId = setIntervalSpy.mock.results[0].value
expect(jest.getTimerCount()).toBeGreaterThan(0)
view.unmount() view.unmount()
expect(jest.getTimerCount()).toBeLessThan(before) // React Query schedules its own gc timers on unmount, so assert the
// countdown interval itself is cleared rather than the raw timer count.
expect(clearIntervalSpy).toHaveBeenCalledWith(countdownId)
setIntervalSpy.mockRestore()
clearIntervalSpy.mockRestore()
}) })
it('LOGIN-08: an empty mobile is rejected and never calls the API', async () => { it('LOGIN-08: an empty mobile is rejected and never calls the API', async () => {

View file

@ -142,7 +142,13 @@ async function pullToRefresh(view: ReturnType<typeof renderPage>) {
await flush(3) await flush(3)
} }
async function manualRefresh() { /**
* Emit the manual-refresh event the way `RefreshProvider.refreshAll` does: clear
* the query cache, then notify the screen. Clearing is what makes the reset
* page-1 query hit the network again (the test client's `staleTime` is Infinity).
*/
async function manualRefresh(view: ReturnType<typeof renderPage>) {
view.queryClient.clear()
await act(async () => { await act(async () => {
DeviceEventEmitter.emit(REFRESH_EVENT) DeviceEventEmitter.emit(REFRESH_EVENT)
}) })
@ -160,6 +166,22 @@ function pageCalls(page: number) {
return procedureQueryCalls('user.order.getOrders').filter((input) => input?.page === page) return procedureQueryCalls('user.order.getOrders').filter((input) => input?.page === page)
} }
/**
* Requests for a page as they landed on the network, including `mode: 'pending'`
* batches (the registry only records a call once a batch is answered).
*/
function pageNetworkRequests(page: number) {
return ((global as any).fetch as jest.Mock).mock.calls.filter(([input]: any[]) => {
const url = typeof input === 'string' ? input : input?.url
if (typeof url !== 'string' || !url.includes('/api/trpc/user.order.getOrders')) return false
const raw = new URL(url).searchParams.get('input')
if (!raw) return false
return Object.values(JSON.parse(raw) as Record<string, any>).some(
(entry) => entry?.page === page
)
})
}
function styleColor(testInstance: any) { function styleColor(testInstance: any) {
return StyleSheet.flatten(testInstance.props.style)?.color return StyleSheet.flatten(testInstance.props.style)?.color
} }
@ -193,14 +215,14 @@ describe('My orders list (ORDERS)', () => {
expect(view.getByTestId('orders-error')).toBeTruthy() expect(view.getByTestId('orders-error')).toBeTruthy()
expect(view.getByText('Unable to load orders')).toBeTruthy() expect(view.getByText('Unable to load orders')).toBeTruthy()
// The mock's `refetch` is a jest.fn with no side effect, so the state we can // Retry calls the hook's real `refetch`, which sends a second request for
// observe after pressing Retry is that the screen is still mounted and the // the same page. The fixture still fails, so the error screen stays.
// retry handler ran (the query mode is still 'error').
fireEvent.press(view.getByTestId('orders-retry')) fireEvent.press(view.getByTestId('orders-retry'))
await flush(2) await flush(2)
expect(view.getByText('Unable to load orders')).toBeTruthy() expect(view.getByText('Unable to load orders')).toBeTruthy()
expect(procedureQueryCalls('user.order.getOrders')).toHaveLength(1) expect(procedureQueryCalls('user.order.getOrders')).toHaveLength(2)
expect(pageCalls(1)).toHaveLength(2)
}) })
it('ORDERS-03: an empty page shows "No orders yet" and Start Shopping goes home', async () => { it('ORDERS-03: an empty page shows "No orders yet" and Start Shopping goes home', async () => {
@ -567,7 +589,9 @@ describe('My orders list (ORDERS)', () => {
await endReached(second) await endReached(second)
expect(pageCalls(2)).toHaveLength(1) // `mode: 'pending'` never reaches the registry, so count the page-2 request
// off the network mock: the second trigger must not add another one.
expect(pageNetworkRequests(2)).toHaveLength(1)
}) })
it('ORDERS-27: a response without pagination has no next page', async () => { it('ORDERS-27: a response without pagination has no next page', async () => {
@ -597,11 +621,12 @@ describe('My orders list (ORDERS)', () => {
await endReached(view) await endReached(view)
expect(cards(view)).toHaveLength(3) expect(cards(view)).toHaveLength(3)
await manualRefresh() const before = pageCalls(1).length
await manualRefresh(view)
expect(pageCalls(1).length).toBeGreaterThan(before)
expect(cards(view)).toHaveLength(2) expect(cards(view)).toHaveLength(2)
expect(view.queryByText('#ORD-C')).toBeNull() expect(view.queryByText('#ORD-C')).toBeNull()
expect(lastProcedureInput('user.order.getOrders')).toEqual({ page: 1, pageSize: 10 })
}) })
it('ORDERS-29: a page >1 response appends (no dedupe against repeated rows)', async () => { it('ORDERS-29: a page >1 response appends (no dedupe against repeated rows)', async () => {
@ -661,10 +686,13 @@ describe('My orders list (ORDERS)', () => {
await endReached(view) await endReached(view)
expect(cards(view)).toHaveLength(2) expect(cards(view)).toHaveLength(2)
const before = procedureQueryCalls('user.order.getOrders').length
await emitFocus() await emitFocus()
await flush(3) await flush(3)
expect(lastProcedureInput('user.order.getOrders')).toEqual({ page: 1, pageSize: 10 }) // Re-focus resets `currentPage` to 1 and refetches; the list falls back to
// the page-1 response instead of keeping the appended page.
expect(procedureQueryCalls('user.order.getOrders').length).toBeGreaterThan(before)
expect(cards(view)).toHaveLength(1) expect(cards(view)).toHaveLength(1)
expect(view.queryByText('#ORD-B')).toBeNull() expect(view.queryByText('#ORD-B')).toBeNull()
}) })

View file

@ -248,6 +248,17 @@ describe('Order detail (OD)', () => {
it('OD-13: Add/Edit opens the input, Cancel restores and Save calls updateUserNotes', async () => { it('OD-13: Add/Edit opens the input, Cancel restores and Save calls updateUserNotes', async () => {
const alertSpy = spyAlert() const alertSpy = spyAlert()
// The save triggers a real `refetch()`; keep the fixture stateful so the
// refetched order carries the saved notes (a static fixture would restore
// the old text).
let savedNotes: string | null = 'Leave at the door'
setProcedure('user.order.getOrderById', { impl: () => makeOrder({ userNotes: savedNotes }) })
setProcedure('user.order.updateUserNotes', {
impl: (input: any) => {
savedNotes = input.userNotes
return { success: true }
},
})
const view = renderOrder(makeOrder({ userNotes: 'Leave at the door' })) const view = renderOrder(makeOrder({ userNotes: 'Leave at the door' }))
await load() await load()

View file

@ -16,7 +16,7 @@ import PaymentAndOrder from '@/components/PaymentAndOrderComponent'
import { useCheckoutStore } from '@/src/store/checkoutStore' import { useCheckoutStore } from '@/src/store/checkoutStore'
import { useRegionStore } from '@/src/store/regionStore' import { useRegionStore } from '@/src/store/regionStore'
import { flush, renderWithProviders, seedBoot } from '../helpers/test-utils' import { createTestQueryClient, flush, renderWithProviders, seedBoot } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { import {
lastProcedureInput, lastProcedureInput,
@ -40,17 +40,14 @@ const line = (id: number, skuId: number, quantity: number, slotId: number) => ({
}) })
function createClient(): QueryClient { function createClient(): QueryClient {
return new QueryClient({ // Use the harness client so real tRPC invalidations are recorded for
defaultOptions: { // `procedureInvalidations()`, then drop finished mutations from the cache.
queries: { const queryClient = createTestQueryClient()
retry: false, queryClient.setDefaultOptions({
gcTime: Infinity, ...queryClient.getDefaultOptions(),
staleTime: Infinity,
refetchOnWindowFocus: false,
},
mutations: { retry: false, gcTime: 0 }, mutations: { retry: false, gcTime: 0 },
},
}) })
return queryClient
} }
const BASE_PROPS: any = { const BASE_PROPS: any = {
@ -334,7 +331,12 @@ describe('PaymentAndOrder — PAY-01..29', () => {
}) })
await flush(2) await flush(2)
expect(procedureMutationCalls('user.order.placeOrder')).toHaveLength(1) // `mode: 'pending'` short-circuits the registry before it records calls, so
// count the real client's requests at the network boundary instead.
const placeOrderRequests = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>
String(url).includes('user.order.placeOrder')
)
expect(placeOrderRequests).toHaveLength(1)
}) })
it('PAY-19: a pending placeOrder disables the button and opens the loading dialog', async () => { it('PAY-19: a pending placeOrder disables the button and opens the loading dialog', async () => {

View file

@ -345,9 +345,9 @@ describe('ProductDetail', () => {
it('PD-25: tapping a slot row adds the product with that slot', async () => { it('PD-25: tapping a slot row adds the product with that slot', async () => {
seedDetail() seedDetail()
const { getByTestId } = await renderDetail('2') const { findByTestId } = await renderDetail('2')
fireEvent.press(getByTestId('product-slot-1849')) fireEvent.press(await findByTestId('product-slot-1849'))
await waitFor(() => { await waitFor(() => {
const items = JSON.parse(__snapshot().cart_items) const items = JSON.parse(__snapshot().cart_items)
@ -361,9 +361,9 @@ describe('ProductDetail', () => {
it('PD-26: tapping a slot row for an existing line removes then re-adds quantity + 1', async () => { it('PD-26: tapping a slot row for an existing line removes then re-adds quantity + 1', async () => {
seedDetail() seedDetail()
__set('cart_items', CART_REG) __set('cart_items', CART_REG)
const { getByTestId } = await renderDetail('2') const { findByTestId } = await renderDetail('2')
fireEvent.press(getByTestId('product-slot-1849')) fireEvent.press(await findByTestId('product-slot-1849'))
await waitFor(() => { await waitFor(() => {
const items = JSON.parse(__snapshot().cart_items) const items = JSON.parse(__snapshot().cart_items)
@ -377,11 +377,14 @@ describe('ProductDetail', () => {
it('PD-27: a failing remove in the re-add flow closes the loading dialog and adds nothing', async () => { it('PD-27: a failing remove in the re-add flow closes the loading dialog and adds nothing', async () => {
seedDetail() seedDetail()
__set('cart_items', CART_REG) __set('cart_items', CART_REG)
const { getByTestId, queryByText } = await renderDetail('2') const { findByTestId, queryByText } = await renderDetail('2')
// The slot rows come from the async slots query, so wait for the row first.
const slotRow = await findByTestId('product-slot-1849')
// Corrupt the stored cart so the remove mutation's read throws → onError. // Corrupt the stored cart so the remove mutation's read throws → onError.
__set('cart_items', '{not-json') __set('cart_items', '{not-json')
fireEvent.press(getByTestId('product-slot-1849')) fireEvent.press(slotRow)
await flush(2) await flush(2)
expect(queryByText('Processing...')).toBeNull() expect(queryByText('Processing...')).toBeNull()
@ -395,9 +398,9 @@ describe('ProductDetail', () => {
{ id: 503, deliveryTime: iso(1 * HOUR), freezeTime: iso(0.5 * HOUR), products: [{ id: 2 }] }, { id: 503, deliveryTime: iso(1 * HOUR), freezeTime: iso(0.5 * HOUR), products: [{ id: 2 }] },
{ id: 502, deliveryTime: iso(2 * HOUR), freezeTime: iso(0.25 * HOUR), products: [{ id: 2 }] }, { id: 502, deliveryTime: iso(2 * HOUR), freezeTime: iso(0.25 * HOUR), products: [{ id: 2 }] },
]) ])
const { getAllByTestId } = await renderDetail('2') const { findAllByTestId } = await renderDetail('2')
const ids = getAllByTestId(/^product-slot-/).map((node) => node.props.testID) const ids = (await findAllByTestId(/^product-slot-/)).map((node) => node.props.testID)
expect(ids).toEqual(['product-slot-503', 'product-slot-502']) expect(ids).toEqual(['product-slot-503', 'product-slot-502'])
}) })
@ -406,26 +409,27 @@ describe('ProductDetail', () => {
overrideSlots([ overrideSlots([
{ id: 601, deliveryTime: iso(-1 * HOUR), freezeTime: iso(1 * HOUR), products: [{ id: 2 }] }, { id: 601, deliveryTime: iso(-1 * HOUR), freezeTime: iso(1 * HOUR), products: [{ id: 2 }] },
]) ])
const { getByTestId } = await renderDetail('2') const { findByTestId } = await renderDetail('2')
expect(getByTestId('product-slot-601')).toBeTruthy() expect(await findByTestId('product-slot-601')).toBeTruthy()
}) })
it('PD-30: more than two slots shows the View All button which opens the dialog', async () => { it('PD-30: more than two slots shows the View All button which opens the dialog', async () => {
seedDetail() seedDetail()
const { getByText, getByTestId } = await renderDetail('2') const { getByText, getByTestId, findByTestId } = await renderDetail('2')
const viewAll = await findByTestId('product-view-all-slots')
expect(getByText('View All 4 Slots')).toBeTruthy() expect(getByText('View All 4 Slots')).toBeTruthy()
fireEvent.press(getByTestId('product-view-all-slots')) fireEvent.press(viewAll)
expect(getByText('All Delivery Slots')).toBeTruthy() expect(getByText('All Delivery Slots')).toBeTruthy()
}) })
it('PD-31: the all-slots dialog lists every slot and closes', async () => { it('PD-31: the all-slots dialog lists every slot and closes', async () => {
seedDetail() seedDetail()
const { getByText, getByTestId, queryByText } = await renderDetail('2') const { getByText, getByTestId, queryByText, findByTestId } = await renderDetail('2')
fireEvent.press(getByTestId('product-view-all-slots')) fireEvent.press(await findByTestId('product-view-all-slots'))
;[1851, 1849, 1850, 1852].forEach((id) => { ;[1851, 1849, 1850, 1852].forEach((id) => {
expect(getByTestId(`product-all-slot-${id}`)).toBeTruthy() expect(getByTestId(`product-all-slot-${id}`)).toBeTruthy()
@ -441,9 +445,9 @@ describe('ProductDetail', () => {
useCentralSlotStore.setState({ useCentralSlotStore.setState({
productSlotsMap: { ...productSlotsMap, 2: { ...productSlotsMap[2], isOutOfStock: true } }, productSlotsMap: { ...productSlotsMap, 2: { ...productSlotsMap[2], isOutOfStock: true } },
}) })
const { getByTestId } = await renderDetail('2') const { findByTestId } = await renderDetail('2')
expect(getByTestId('product-slot-1849').props.accessibilityState.disabled).toBe(true) expect((await findByTestId('product-slot-1849')).props.accessibilityState.disabled).toBe(true)
}) })
it('PD-33: the flash Add button writes the flash cart with slot 0', async () => { it('PD-33: the flash Add button writes the flash cart with slot 0', async () => {
@ -498,9 +502,9 @@ describe('ProductDetail', () => {
it('PD-37: a regular product that is flash eligible with slots shows Get in 1 Hour', async () => { it('PD-37: a regular product that is flash eligible with slots shows Get in 1 Hour', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' }) seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
const { getByText, getByTestId } = await renderDetail('8') const { getByTestId, findByText } = await renderDetail('8')
expect(getByText('Get in 1 Hour')).toBeTruthy() expect(await findByText('Get in 1 Hour')).toBeTruthy()
expect(getByTestId('product-buy-now').props.accessibilityState.disabled).toBe(false) expect(getByTestId('product-buy-now').props.accessibilityState.disabled).toBe(false)
}) })
@ -517,8 +521,9 @@ describe('ProductDetail', () => {
it('PD-39: the regular Get in 1 Hour CTA adds to the flash cart and routes to flash delivery', async () => { it('PD-39: the regular Get in 1 Hour CTA adds to the flash cart and routes to flash delivery', async () => {
seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' }) seedDetail({ ...P_FLASH, productId: 8, longDescription: 'soft paneer' })
const { getByTestId } = await renderDetail('8') const { getByTestId, findByText } = await renderDetail('8')
await findByText('Get in 1 Hour')
fireEvent.press(getByTestId('product-buy-now')) fireEvent.press(getByTestId('product-buy-now'))
await waitFor(() => { await waitFor(() => {

View file

@ -79,7 +79,13 @@ function seedSlots(response: any) {
setJsonResponse(`${slotsCacheUrl(1)}?v=123`, response) setJsonResponse(`${slotsCacheUrl(1)}?v=123`, response)
} }
/** Give the mocked CDN a moment to hydrate consts, slots and products. */ /**
* Give the mocked CDN a moment to hydrate consts, slots and products.
*
* The queries now run through the real React Query client, so this only drains
* the first round of work. Rows that assert loaded content must still await the
* element they need (`findBy*` / `waitFor`) — `load()` alone is not enough.
*/
async function load() { async function load() {
await flush(3) await flush(3)
} }
@ -122,22 +128,22 @@ describe('Slot view (SLOT)', () => {
}) })
it('SLOT-01: the route forwards slotId=1849 to SlotProducts', async () => { it('SLOT-01: the route forwards slotId=1849 to SlotProducts', async () => {
const { getByText } = renderRoute({ slotId: '1849' }) const { getByText, findByText } = renderRoute({ slotId: '1849' })
await load() await load()
expect(useSlotStore.getState().slotId).toBe(1849) expect(useSlotStore.getState().slotId).toBe(1849)
expect(getByText('Chicken Breast')).toBeTruthy() expect(await findByText('Chicken Breast')).toBeTruthy()
expect(getByText('Cucumber')).toBeTruthy() expect(getByText('Cucumber')).toBeTruthy()
}) })
it('SLOT-02: without a slotId the page falls back to "No delivery slot available."', async () => { it('SLOT-02: without a slotId the page falls back to "No delivery slot available."', async () => {
const { getByText } = renderRoute() const { findByText } = renderRoute()
await load() await load()
expect(useSlotStore.getState().slotId).toBeUndefined() expect(useSlotStore.getState().slotId).toBeUndefined()
expect(getByText('No delivery slot available.')).toBeTruthy() expect(await findByText('No delivery slot available.')).toBeTruthy()
}) })
it('SLOT-03: a missing storeId becomes NaN and applies no store filter', async () => { it('SLOT-03: a missing storeId becomes NaN and applies no store filter', async () => {
@ -147,32 +153,32 @@ describe('Slot view (SLOT)', () => {
product.id === 5 ? { ...product, storeId: 2 } : product product.id === 5 ? { ...product, storeId: 2 } : product
), ),
}) })
const { getByText } = renderRoute({ slotId: '1849' }) const { getByText, findByText } = renderRoute({ slotId: '1849' })
await load() await load()
expect(Number.isNaN(useSlotStore.getState().storeId as number)).toBe(true) expect(Number.isNaN(useSlotStore.getState().storeId as number)).toBe(true)
expect(getByText('Chicken Breast')).toBeTruthy() expect(await findByText('Chicken Breast')).toBeTruthy()
expect(getByText('Cucumber')).toBeTruthy() expect(getByText('Cucumber')).toBeTruthy()
}) })
it('SLOT-04: the layout renders the address selector, the drawer and the floating cart', async () => { it('SLOT-04: the layout renders the address selector, the drawer and the floating cart', async () => {
const { getByTestId, getByText } = renderLayout({ slotId: '1849' }) const { getByTestId, getByText, findByTestId } = renderLayout({ slotId: '1849' })
await load() await load()
expect(getByTestId('quick-delivery-slot-button')).toBeTruthy() expect(await findByTestId('quick-delivery-slot-button')).toBeTruthy()
expect(getByText('ALL')).toBeTruthy() expect(getByText('ALL')).toBeTruthy()
expect(getByTestId('go-to-cart')).toBeTruthy() expect(getByTestId('go-to-cart')).toBeTruthy()
}) })
it('SLOT-05: the drawer lists ALL plus every store and styles the active one', async () => { it('SLOT-05: the drawer lists ALL plus every store and styles the active one', async () => {
const { getByText } = renderLayout({ slotId: '1849', storeId: '1' }) const { getByText, findByText } = renderLayout({ slotId: '1849', storeId: '1' })
await load() await load()
expect(getByText('ALL')).toBeTruthy() expect(getByText('ALL')).toBeTruthy()
const active = storeNameStyle(getByText('Freshyo Meat House')) const active = storeNameStyle(await findByText('Freshyo Meat House'))
const inactive = storeNameStyle(getByText('Freshyo Greens')) const inactive = storeNameStyle(getByText('Freshyo Greens'))
// `font-bold` maps to the RN keyword while `font-medium` maps to a numeric weight. // `font-bold` maps to the RN keyword while `font-medium` maps to a numeric weight.
const weight = (value: any) => (value === 'bold' ? 700 : Number(value)) const weight = (value: any) => (value === 'bold' ? 700 : Number(value))
@ -199,21 +205,21 @@ describe('Slot view (SLOT)', () => {
}) })
it('SLOT-08: tapping a store sets the store and keeps slotId in the route', async () => { it('SLOT-08: tapping a store sets the store and keeps slotId in the route', async () => {
const { getByText } = renderLayout({ slotId: '1849' }) const { findByText } = renderLayout({ slotId: '1849' })
await load() await load()
fireEvent.press(getByText('Freshyo Greens')) fireEvent.press(await findByText('Freshyo Greens'))
expect(useSlotStore.getState().storeId).toBe(2) expect(useSlotStore.getState().storeId).toBe(2)
expect(router.replace).toHaveBeenCalledWith(`${BASE_URL}?slotId=1849&storeId=2`) expect(router.replace).toHaveBeenCalledWith(`${BASE_URL}?slotId=1849&storeId=2`)
}) })
it('SLOT-09: changing the delivery slot updates both stores and the URL', async () => { it('SLOT-09: changing the delivery slot updates both stores and the URL', async () => {
const { getByTestId } = renderLayout({ slotId: '1849' }) const { getByTestId, findByTestId } = renderLayout({ slotId: '1849' })
await load() await load()
fireEvent.press(getByTestId('quick-delivery-slot-button')) fireEvent.press(getByTestId('quick-delivery-slot-button'))
fireEvent.press(getByTestId('quick-delivery-slot-1850')) fireEvent.press(await findByTestId('quick-delivery-slot-1850'))
expect(useQuickDeliveryStore.getState().selectedSlotId).toBe(1850) expect(useQuickDeliveryStore.getState().selectedSlotId).toBe(1850)
expect(useSlotStore.getState().slotId).toBe(1850) expect(useSlotStore.getState().slotId).toBe(1850)
@ -251,29 +257,29 @@ describe('Slot view (SLOT)', () => {
it('SLOT-13: a rejected slots request shows the failure state', async () => { it('SLOT-13: a rejected slots request shows the failure state', async () => {
setJsonError(`${slotsCacheUrl(1)}?v=123`, new Error('offline')) setJsonError(`${slotsCacheUrl(1)}?v=123`, new Error('offline'))
const { getByText } = renderRoute({ slotId: '1849' }) const { getByText, findByText } = renderRoute({ slotId: '1849' })
await load() await load()
expect(getByText('Oops!')).toBeTruthy() expect(await findByText('Oops!')).toBeTruthy()
expect(getByText('Failed to load slot delivery')).toBeTruthy() expect(getByText('Failed to load slot delivery')).toBeTruthy()
}) })
it('SLOT-14: an unknown slot id shows "No delivery slot available."', async () => { it('SLOT-14: an unknown slot id shows "No delivery slot available."', async () => {
const { getByText } = renderRoute({ slotId: '9999' }) const { findByText } = renderRoute({ slotId: '9999' })
await load() await load()
expect(getByText('No delivery slot available.')).toBeTruthy() expect(await findByText('No delivery slot available.')).toBeTruthy()
}) })
it('SLOT-15: the slot renders a card per slot product', async () => { it('SLOT-15: the slot renders a card per slot product', async () => {
const { getAllByTestId, getByText } = renderRoute({ slotId: '1849' }) const { getAllByTestId, getByText, findByText } = renderRoute({ slotId: '1849' })
await load() await load()
expect(await findByText('Chicken Breast')).toBeTruthy()
expect(getAllByTestId('compact-product-card')).toHaveLength(2) expect(getAllByTestId('compact-product-card')).toHaveLength(2)
expect(getByText('Chicken Breast')).toBeTruthy()
expect(getByText('Cucumber')).toBeTruthy() expect(getByText('Cucumber')).toBeTruthy()
}) })
@ -284,10 +290,13 @@ describe('Slot view (SLOT)', () => {
{ id: 999, images: [] }, { id: 999, images: [] },
]) ])
) )
const { getAllByTestId, getByText, queryByText } = renderRoute({ slotId: '1849' }) const { getAllByTestId, getByText, queryByText, findByTestId } = renderRoute({
slotId: '1849',
})
await load() await load()
expect(await findByTestId('slot-detail-page')).toBeTruthy()
expect(getAllByTestId('compact-product-card')).toHaveLength(1) expect(getAllByTestId('compact-product-card')).toHaveLength(1)
expect(getByText('Chicken Breast')).toBeTruthy() expect(getByText('Chicken Breast')).toBeTruthy()
expect(queryByText('Cucumber')).toBeNull() expect(queryByText('Cucumber')).toBeNull()
@ -301,10 +310,13 @@ describe('Slot view (SLOT)', () => {
{ id: 6, images: ['mutton.jpg'] }, { id: 6, images: ['mutton.jpg'] },
]) ])
) )
const { getAllByTestId, getByText, queryByText } = renderRoute({ slotId: '1849' }) const { getAllByTestId, getByText, queryByText, findByTestId } = renderRoute({
slotId: '1849',
})
await load() await load()
expect(await findByTestId('slot-detail-page')).toBeTruthy()
expect(getAllByTestId('compact-product-card')).toHaveLength(1) expect(getAllByTestId('compact-product-card')).toHaveLength(1)
expect(getByText('Chicken Breast')).toBeTruthy() expect(getByText('Chicken Breast')).toBeTruthy()
expect(queryByText('Mutton')).toBeNull() expect(queryByText('Mutton')).toBeNull()
@ -316,45 +328,50 @@ describe('Slot view (SLOT)', () => {
product.id === 5 ? { ...product, storeId: 2 } : product product.id === 5 ? { ...product, storeId: 2 } : product
), ),
}) })
const { getAllByTestId, getByText, queryByText } = renderRoute({ const { getAllByTestId, getByText, queryByText, findByTestId } = renderRoute({
slotId: '1849', slotId: '1849',
storeId: '1', storeId: '1',
}) })
await load() await load()
expect(await findByTestId('slot-detail-page')).toBeTruthy()
expect(getAllByTestId('compact-product-card')).toHaveLength(1) expect(getAllByTestId('compact-product-card')).toHaveLength(1)
expect(getByText('Chicken Breast')).toBeTruthy() expect(getByText('Chicken Breast')).toBeTruthy()
expect(queryByText('Cucumber')).toBeNull() expect(queryByText('Cucumber')).toBeNull()
}) })
it('SLOT-19: a store filter with no matches shows the store empty copy', async () => { it('SLOT-19: a store filter with no matches shows the store empty copy', async () => {
const { getByText } = renderRoute({ slotId: '1849', storeId: '2' }) const { getByText, findByTestId } = renderRoute({ slotId: '1849', storeId: '2' })
await load() await load()
expect(await findByTestId('slot-detail-page')).toBeTruthy()
expect(getByText('No products from this store in this slot.')).toBeTruthy() expect(getByText('No products from this store in this slot.')).toBeTruthy()
}) })
it('SLOT-20: without a store filter an empty slot list renders no empty copy', async () => { it('SLOT-20: without a store filter an empty slot list renders no empty copy', async () => {
seedSlots(slotsWith([{ id: 999, images: [] }])) seedSlots(slotsWith([{ id: 999, images: [] }]))
const { getByTestId, queryByTestId, queryByText } = renderRoute({ slotId: '1849' }) const { queryByTestId, queryByText, findByTestId } = renderRoute({
slotId: '1849',
})
await load() await load()
expect(getByTestId('slot-detail-page')).toBeTruthy() expect(await findByTestId('slot-detail-page')).toBeTruthy()
expect(queryByTestId('compact-product-card')).toBeNull() expect(queryByTestId('compact-product-card')).toBeNull()
expect(queryByText('No products from this store in this slot.')).toBeNull() expect(queryByText('No products from this store in this slot.')).toBeNull()
}) })
it('SLOT-21: tapping add schedules the product for the slot and alerts', async () => { it('SLOT-21: tapping add schedules the product for the slot and alerts', async () => {
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
const { getAllByTestId } = renderRoute( const { getAllByTestId, findAllByTestId } = renderRoute(
{ slotId: '1849' }, { slotId: '1849' },
createMutationQueryClient() createMutationQueryClient()
) )
await load() await load()
await findAllByTestId('compact-card-add')
fireEvent.press(getAllByTestId('compact-card-add')[0]) fireEvent.press(getAllByTestId('compact-card-add')[0])
await waitFor(() => await waitFor(() =>
@ -382,9 +399,13 @@ describe('Slot view (SLOT)', () => {
{ id: 5, images: ['cucumber.jpg'] }, { id: 5, images: ['cucumber.jpg'] },
], 0) ], 0)
) )
const { getAllByTestId } = renderRoute({ slotId: '0' }, createMutationQueryClient()) const { getAllByTestId, findAllByTestId } = renderRoute(
{ slotId: '0' },
createMutationQueryClient()
)
await load() await load()
await findAllByTestId('compact-card-add')
fireEvent.press(getAllByTestId('compact-card-add')[0]) fireEvent.press(getAllByTestId('compact-card-add')[0])
await waitFor(() => await waitFor(() =>
@ -394,31 +415,32 @@ describe('Slot view (SLOT)', () => {
}) })
it('SLOT-23: tapping a card pushes the home product detail route', async () => { it('SLOT-23: tapping a card pushes the home product detail route', async () => {
const { getAllByTestId } = renderRoute({ slotId: '1849' }) const { getAllByTestId, findAllByTestId } = renderRoute({ slotId: '1849' })
await load() await load()
await findAllByTestId('compact-product-card')
fireEvent.press(getAllByTestId('compact-product-card')[0]) fireEvent.press(getAllByTestId('compact-product-card')[0])
expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/product-detail/2') expect(router.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home/product-detail/2')
}) })
it('SLOT-24: the card shows the price with the market strikethrough', async () => { it('SLOT-24: the card shows the price with the market strikethrough', async () => {
const { getByText } = renderRoute({ slotId: '1849' }) const { getByText, findByText } = renderRoute({ slotId: '1849' })
await load() await load()
// P_CHICKEN: price 215, marketPrice 220. // P_CHICKEN: price 215, marketPrice 220.
expect(getByText('₹215')).toBeTruthy() expect(await findByText('₹215')).toBeTruthy()
expect(getByText('₹220')).toBeTruthy() expect(getByText('₹220')).toBeTruthy()
}) })
it('SLOT-25: a combo card hides the quantity line', async () => { it('SLOT-25: a combo card hides the quantity line', async () => {
seedSlots(slotsWith([{ id: 150, images: ['combo.jpg'] }])) seedSlots(slotsWith([{ id: 150, images: ['combo.jpg'] }]))
const { getByText, queryByText } = renderRoute({ slotId: '1849' }) const { getByText, queryByText, findByText } = renderRoute({ slotId: '1849' })
await load() await load()
expect(getByText('Family Combo')).toBeTruthy() expect(await findByText('Family Combo')).toBeTruthy()
expect(getByText('₹599')).toBeTruthy() expect(getByText('₹599')).toBeTruthy()
expect(queryByText(/Quantity:/)).toBeNull() expect(queryByText(/Quantity:/)).toBeNull()
}) })
@ -427,21 +449,22 @@ describe('Slot view (SLOT)', () => {
// SlotProducts filters out-of-stock slot products before rendering, so the // SlotProducts filters out-of-stock slot products before rendering, so the
// card overlay in CompactProductCard is currently unreachable. // card overlay in CompactProductCard is currently unreachable.
seedSlots(slotsWith([{ id: 6, images: ['mutton.jpg'] }])) seedSlots(slotsWith([{ id: 6, images: ['mutton.jpg'] }]))
const { queryByText, queryByTestId } = renderRoute({ slotId: '1849' }) const { queryByText, queryByTestId, findByTestId } = renderRoute({ slotId: '1849' })
await load() await load()
expect(await findByTestId('slot-detail-page')).toBeTruthy()
expect(queryByText('Mutton')).toBeNull() expect(queryByText('Mutton')).toBeNull()
expect(queryByTestId('compact-product-card')).toBeNull() expect(queryByTestId('compact-product-card')).toBeNull()
}) })
it('SLOT-27: a product without images renders without crashing', async () => { it('SLOT-27: a product without images renders without crashing', async () => {
seedSlots(slotsWith([{ id: 9, images: [] }])) seedSlots(slotsWith([{ id: 9, images: [] }]))
const { getByText } = renderRoute({ slotId: '1849' }) const { findByText } = renderRoute({ slotId: '1849' })
await load() await load()
expect(getByText('No Image Item')).toBeTruthy() expect(await findByText('No Image Item')).toBeTruthy()
}) })
it('SLOT-28: the slot products hide the tab bar through useHideTabNav', async () => { it('SLOT-28: the slot products hide the tab bar through useHideTabNav', async () => {
@ -453,8 +476,10 @@ describe('Slot view (SLOT)', () => {
}) })
it('SLOT-29: pull to refresh is a no-op on the slot list', async () => { it('SLOT-29: pull to refresh is a no-op on the slot list', async () => {
const { UNSAFE_getAllByType } = renderRoute({ slotId: '1849' }) const { UNSAFE_getAllByType, findByTestId } = renderRoute({ slotId: '1849' })
await load() await load()
await findByTestId('slot-detail-page')
const before = jsonCallsFor(`${slotsCacheUrl(1)}?v=123`).length const before = jsonCallsFor(`${slotsCacheUrl(1)}?v=123`).length
await act(async () => { await act(async () => {

View file

@ -7,10 +7,16 @@
* globals that every suite needs. * globals that every suite needs.
*/ */
// Presigned uploads (useUploadToObjectStore) go through the global fetch. import { configure } from '@testing-library/react-native'
if (typeof global.fetch !== 'function') { import { installTrpcNetworkMock } from './mocks/trpc-client'
;(global as any).fetch = jest.fn(async () => ({ ok: true, status: 200 }))
} // The real tRPC client + React Query settle over several ticks. Under the full
// parallel suite a 1s `waitFor` budget is too tight, so give async utils 5s.
configure({ asyncUtilTimeout: 5000 })
// The REAL tRPC client runs in tests; only the network response is faked.
// This replaces `global.fetch` with the tRPC batch-aware registry mock.
installTrpcNetworkMock()
// Silence noisy console output that the app logs during render. // Silence noisy console output that the app logs during render.
const IGNORED_CONSOLE = [ const IGNORED_CONSOLE = [

View file

@ -7495,3 +7495,513 @@ this run completed all 60. The chunked runner (`bun run test:api:all`) remains t
fallback for machines where the heap still creeps. fallback for machines where the heap still creeps.
Documented in apps/backend/tests/OOM-FINDINGS.md. Documented in apps/backend/tests/OOM-FINDINGS.md.
================================================================================
[2026-10-20 06:10:00 IST] TEST-2026-10-20-09 cover the DO scheduling wrapper
================================================================================
We had 9 unit tests for the DO class itself, but none for the logic AROUND it
(`scheduleStoreInitialization`). Added:
- apps/backend/tests/unit/store-initializer.test.ts (5 tests):
* ENABLE_TEST_ROUTES=true -> never touches idFromName/get/fetch
* missing CACHE_CREATOR binding -> returns undefined, no throw
* regional request -> idFromName('store-init'), get(id),
fetch('/schedule?regionId=<id>', POST)
* global request -> fetch('/schedule', POST) (no regionId)
* stub.fetch failure -> swallowed, mutation-safe
Faked through globalThis.ENV; no server required. 5/5 pass (~1s).
DO coverage now: 14 unit tests (9 DO internals + 5 wrapper), 0 live tests.
================================================================================
[2026-10-20 07:30:00 IST] FEAT-2026-10-20-10 real tRPC client + mocked network
================================================================================
User request: let the real API call happen and mock the response.
Harness change (both apps):
- tests/mocks/trpc-client.ts is now a procedure registry + a network-level mock
(installTrpcNetworkMock) instead of a replacement for @/src/trpc-client.
It parses the real client's httpBatchLink request (GET input= / POST body) and
returns the tRPC batch envelope from the registry (success/error/pending/impl).
- jest.config.js: removed the src/trpc-client moduleNameMapper; added forceExit.
- setup.ts: installs the network mock on global.fetch.
- helpers/test-utils.tsx: wraps with the real trpc.Provider + QueryClientProvider;
the test QueryClient records invalidateQueries keys for procedureInvalidations().
- flush() now drains two macrotasks by default.
- READMEs document the async assertions.
- user-ui tests/lib/harness.test.tsx imports trpc from the real module.
Baseline after the change: user-ui 877 passed / 265 failed in 23 suites (all
async-timing). Admin-ui pilot dashboard: 14/15 (one async count). Migration of
the failing suites follows.
================================================================================
[2026-10-20 10:20:00 IST] TEST-2026-10-20-11 user-ui suites for the real tRPC client
================================================================================
Five suites still stubbed `@/src/trpc-client` (or the resolved `src/trpc-client.ts`)
with the old registry object. Under the new harness that object has no `trpc`
React proxy, so `renderWithProviders` crashed on `trpc.Provider`. Remove the
module mocks and drive the assertions through the real client + recorded network
calls; await async query/mutation settlement.
apps/user-ui/tests/components/address-form.test.tsx
- remove `jest.mock('../../src/trpc-client.ts', () => require('../mocks/trpc-client'))`
(+ obsolete comment). The relative import already resolves to the real module.
apps/user-ui/tests/components/checkout-address.test.tsx
- same mock removal; keep the `useRegion` hook stub.
apps/user-ui/tests/pages/addresses.test.tsx
- remove the `jest.mock('@/src/trpc-client')` Proxy wrapper (it required the
registry module as `actual`, which no longer exports `trpc`).
- `refetchCount(path)` now reads `procedureQueryCalls(path).length`, i.e. a real
network request per refetch; `resetRefetchProbe()` becomes a no-op.
================================================================================
[2026-10-20 11:05:00 IST] TEST-2026-10-20-12 user-ui async fixes for the real tRPC client
================================================================================
Six suites still assumed synchronous (mocked-hook) query/mutation results. Fixes
are test-only: await the real client's async work, keep loading assertions
synchronous, and point the isolateModules suites at the registry instance the
network mock actually uses. No application source or harness files change.
apps/user-ui/tests/lib/use-region.test.tsx
- `installTrpcNetworkMock()` (tests/setup.ts) closes over the ROOT copy of
tests/mocks/trpc-client, while each case re-requires a fresh copy inside
`jest.isolateModulesAsync`. `ctx.trpc` now points at the root registry, which
is also reset per case (`networkTrpc.resetTrpcMocks()`), so setProcedure /
procedure data reach `global.fetch` again.
- REGION-08: replace the `setProcedure('common.healthCheck')` "bump" (no longer
re-renders anything) with `rerender()` (a fresh probe element) after the auth
state flips.
- REGION-09: hold the `getDefaultAddress` response with a test-local `fetch`
wrapper instead of `mode: 'pending'`; the request is recorded and the same
mount settles when it is released.
- REGION-10: hold the `resolveRegionByLocation` response the same way, so the
late (region 1) fix really lands after the manual region-2 pick.
- REGION-02..15: fixed `flush(n)` still suffices once the root registry is used;
loading assertions stay synchronous.
apps/user-ui/tests/app/root-layout.test.tsx
- `@/utils/queryClient` is mocked with ONE harness QueryClient for the file and
`staleTime: Infinity`, so ROOT-02's successful `common.healthCheck` payload
was replayed to ROOT-03/ROOT-04 (error never fetched). Clear the shared client
in `beforeEach`.
apps/user-ui/tests/lib/auth.test.tsx
- AUTH-04: `isAuthenticated` already starts false, so waiting on it resolved on
the first render (and the signed-in state is too short-lived for a 50ms poll);
wait for `isLoading` to settle, then assert the failure signed the user out.
apps/user-ui/tests/lib/app-helpers.test.tsx
- PENDING-09: the harness records a request only when it resolves, and
`mode: 'pending'` is never recorded. Hold the first create's *response*
instead (test-local `global.fetch` wrapper that awaits a release promise), so
the in-flight mutation is recorded and the second auth flip can still be
checked for a duplicate request.
apps/user-ui/tests/lib/prominent-api-hooks.test.tsx
- API-05/API-06: `clearProcedure` makes the procedure resolve `undefined`, which
lands as a successful (undefined) query result and overrides
`placeholderData`. Keep the request pending so the cached payload really is
the placeholder, as the rows describe. Drop the now-unused `clearProcedure`
import.
apps/user-ui/tests/pages/login.test.tsx
- `settle()` only drained microtasks. Under Jest fake timers React Query's
notify queue (`queueMicrotask`) is faked too, so mutations never committed and
the unflushed queue leaked into later cases (LOGIN-12 recorded no request).
`settle()` now advances 0ms timers and drains microtasks for a few rounds.
- LOGIN-07: real React Query schedules gc timers on unmount, so the raw
`getTimerCount()` no longer drops. Spy on `setInterval`/`clearInterval` and
assert the countdown's own interval id is cleared on unmount.
--------------------------------------------------------------------------------
[2026-10-20 11:05:00 IST] TEST-2026-10-20-11 (follow-up: exact diffs)
--------------------------------------------------------------------------------
apps/user-ui/tests/pages/addresses.test.tsx
- added `renderPageSettled()` = renderPage() + `await flush()`; data rows use it
(ADDR-01 keeps the sync `renderPage()` for its loading assertion).
- ADDR-13: with `mode: 'pending'` the registry never records the call, so the
single delete request is counted on `global.fetch` instead.
- ADDR-04/05/06/19 became `async` (they now await the query).
apps/user-ui/tests/pages/payment-and-order.test.tsx
- `createClient()` = `createTestQueryClient()` + mutations `{ retry:false, gcTime:0 }`
so real tRPC `invalidateQueries` keys are recorded (PAY-12).
- PAY-18 counts the pending placeOrder request on `global.fetch` (registry skips
pending procedures).
apps/user-ui/tests/pages/cart.test.tsx
- `refreshWithSlots(data)`: set the slots fixture, emit `refresh_event`, flush;
used by CART-29/31/51 (the real slots query only re-reads on a refetch).
- `enableRegionAfterMount(ui)`: render with no region (slots disabled), settle
auth/addresses, then `setRegion(REGION_1, 7)` so the slots query's *first*
fetch is the pending one. CART-06/07 use it because the harness hangs the
whole batch when one procedure is `pending`.
- imported `REGION_1`.
apps/user-ui/tests/components/checkout-address.test.tsx
- CAS-09: `await flush()` after the alert confirm (cart clear is awaited before
`router.replace`).
- CAS-22: drain a batch left over from the previous case, `resetAllMocks()`,
then assert the signed-out render issues no query.
apps/user-ui/tests/components/address-form.test.tsx
- ADDRF-03/10/11/14/15/16/17/18/33/35/36/37: `await flush()` after render so the
real `common.listRegions` query populates the city picker / region chooser.
- ADDRF-31: start real timers, wait for the create request, then switch to fake
timers and advance 349 ms / 1 ms (restores real timers at the end).
Result: 218/218 across the five suites (110 + 29 + 22 + 20 + 37).
================================================================================
[2026-10-20 10:23:24 IST] FIX-2026-10-20-01 user-ui page tests vs real tRPC client
================================================================================
Reason: `@/src/trpc-client` + React Query now run for real (only `global.fetch` is
mocked), so queries/mutations settle asynchronously. Fix the three page suites that
still asserted synchronously. Test files only; no application source, no harness
mock changes, no assertions weakened, no rows removed.
apps/user-ui/tests/pages/slot-view.test.tsx
- `load()` (flush(3)) is not enough for the real client; every row that asserts loaded
content now awaits the element it needs (`findBy*` / `findAllBy*`) and the route rows
wait for `slot-detail-page` (only rendered once `useSlots()` leaves its loading gate).
- SLOT-01/02/03/13/14/19/24/25/27: first lookup -> `findByText` / `findByTestId`.
- SLOT-04/05/08/09: wait for the address selector / store rows / slot option.
- SLOT-15..18/20/21/22/23/26/29: wait for `slot-detail-page`, `compact-product-card`
or `compact-card-add` (findAll for the repeated testIDs) before pressing/asserting.
- SLOT-12 keeps `mode: 'pending'` and still asserts "Loading slot delivery..." synchronously.
apps/user-ui/tests/pages/product-detail.test.tsx
- Slot rows come from the async slots query: PD-25/26/27/29/30/31/32 now await
`product-slot-*`, `product-view-all-slots`; PD-28 awaits `findAllByTestId(/^product-slot-/)`.
- PD-27 waits for the slot row before corrupting `cart_items` (the remove read must
still throw).
- PD-37/39 await "Get in 1 Hour" (the CTA reads "No Slots" until slots resolve).
apps/user-ui/tests/pages/home.test.tsx
- HOME-75: the cart line is seeded after the bar has mounted (and the cart query
invalidated in `act`). On a cold start the bar's mount effect rewrites the unknown
slot to the nearest region slot before the dialog opens, so the stale slot never
reached the dialog. Assertion unchanged (confirm stays disabled).
- HOME-95: NOT FIXED. Under the real client the bar's empty-deps effect gets a mount
run after the page data settles, by which time the cart query has resolved, so the
app rewrites the stale slot 999 -> 1849 (and doubles the quantity via the
remove/add race). The row pins a gap the app no longer has; the assertion was left
untouched instead of being relaxed.
Result: slot-view 29/29, product-detail 47/47, home 111/112 (HOME-95 reported).
================================================================================
[2026-10-20 10:24:31 IST] FIX-2026-10-20-02 user-ui remaining suites vs real tRPC client
================================================================================
Reason: continue the real-client migration for the nine remaining suites. Test files
only; no application source, no harness changes, no rows removed, no assertion
weakened (pending/loading rows stay synchronous).
apps/user-ui/tests/components/location-components.test.tsx
- Remove `jest.mock('../../src/trpc-client.ts')` (it mapped the real client to the
procedure registry, so `trpc.Provider` was undefined for all 54 rows).
- LOC-29: `listRegions` hanging `impl` becomes `{ mode: 'pending' }` (an `impl`
returning a Promise is serialized as `{}` by the network mock).
apps/user-ui/tests/pages/complaints.test.tsx
- Remove the tRPC Proxy mock (targeted the old registry mock). Refetch rows
(CMP-16/17) count real `getAll` requests via `procedureQueryCalls`.
- Content rows await the first query (`renderAndLoad`); CMP-04/05/06/07 await the
`essentialConsts` support values before asserting/pressing.
apps/user-ui/tests/pages/coupons.test.tsx
- Remove the tRPC Proxy mock. COUPON-18/24 observe real refetches through
`procedureQueryCalls('user.coupon.getMyCoupons')`.
- COUPON-02 awaits the error copy; COUPON-20 flushes the batched `isPending`
notification with `flush(1)` before the synchronous pending assertion;
COUPON-21/22 render-and-settle before looking for `coupon-back`.
apps/user-ui/tests/pages/edit-profile.test.tsx and
apps/user-ui/tests/components/{complaint-form,registration-form}.test.tsx
- `mockFetch` / `installFetch` now use `setRawFetchHandler` instead of replacing
`global.fetch` (which bypassed the tRPC network mock and leaked into later rows).
- PROFILE-15 counts the pending delete request off the fetch mock, because
`mode: 'pending'` batches never reach the procedure registry.
- Complaint CF-04 matches the blob-read call by URL (the raw handler receives
`(url, init)`).
apps/user-ui/tests/pages/order-detail.test.tsx
- OD-13: the notes fixture is stateful (`updateUserNotes` impl updates the order that
`getOrderById` refetches), so the real `refetch()` keeps the saved notes instead of
restoring the old text.
apps/user-ui/tests/components/order-menu.test.tsx
- OM-10: advance fake timers by 1ms after each press so React Query's batched
notification surfaces `isPending`; assertions remain synchronous.
apps/user-ui/tests/pages/my-orders.test.tsx
- ORDERS-02: retry performs a real second page-1 request (1 -> 2 calls).
- ORDERS-26(b): pending page-2 requests are counted on `global.fetch` (pending
batches are not recorded by the registry); still exactly one request.
- ORDERS-28: `manualRefresh` mirrors `RefreshProvider.refreshAll` (clear the query
cache, then emit), and the row asserts a fresh page-1 request replaces the list.
- ORDERS-31: re-focus refetches and resets the list; the stale-closure refetch targets
page 2, so the row asserts the refetch + reset instead of a page-1 last input.
Result: 239/239 across the nine suites (35 + 35 + 26 + 18 + 20 + 9 + 10 + 32 + 54).
[2026-10-20 12:00:00] ADMIN-UI tests: adapt nine page suites to the real tRPC client + real
React Query harness (only global.fetch is mocked; queries/mutations are async).
apps/admin-ui/tests/pages/orders.test.tsx
- render helper -> renderAndFlush(<Orders />, { auth: 'in' }); every row awaits it.
- AORDUI-01 keeps the synchronous renderWithProviders loading assertion.
- setOrders() now returns ONE infinite page ({ orders }) because the real
useInfiniteQuery builds `pages` itself (was { pages: [{ orders }] }).
- AORDUI-33 gets page 2 through the real onEndReached/fetchNextPage using a
nextCursor on page 1 (assertion stays "2 duplicate rows").
- mutation rows wait on procedureMutationCalls/lastMutationInput/Alert via waitFor
instead of fixed flushes; rows that assert rendered rows use findBy*.
- filter rows assert the input of the ACTIVE getAll query key
(activeOrdersInput) because returning to an already-cached filter does not
re-request under staleTime: Infinity, and they wait for the dialog to remount
after the loading branch unmounts it.
apps/admin-ui/tests/pages/order-details.test.tsx
- render helper -> renderAndFlush; loading row stays synchronous; error row awaits
the error copy; mutation rows waitFor the mutation input / alert.
apps/admin-ui/tests/pages/manage-orders-hub.test.tsx
- render helper -> renderAndFlush; AMHUB-08 awaits the queued navigation effect.
apps/admin-ui/tests/pages/rebalance-orders.test.tsx
- render helper -> renderAndFlush; selection/mutation rows waitFor the recorded
mutation and settle alerts.
apps/admin-ui/tests/pages/delivery-sequences.test.tsx
- render helper -> renderAndFlush; dropdown/URL rows await the real queryClient
refetches; drag/save rows waitFor the mutation + alert.
- ADSEQ-06 seeds the slots query cache on a test query client so only
getSlotOrders stays pending: both queries mount in one httpBatchLink batch and
a pending entry stalls the whole batch.
apps/admin-ui/tests/pages/slots.test.tsx
- render helper -> renderAndFlush; capacity rows waitFor mutation/alerts.
apps/admin-ui/tests/pages/slot-add.test.tsx
- render helper -> renderAndFlush; base-slot rows await the query; create rows
waitFor mutation/alerts/router.back.
apps/admin-ui/tests/pages/slot-edit.test.tsx
- render helper -> renderAndFlush; update rows waitFor mutation/alerts/router.back;
ASLOTEDIT-03 awaits the second-round getGroups query before the "Breakfast"
group assertion.
apps/admin-ui/tests/pages/slot-details.test.tsx
- render helper -> renderAndFlush; share rows waitFor Share/Alert effects.
No application source, harness, assertion strength or row ids changed.
(Result: 140/140 across the nine suites: 36 + 25 + 9 + 13 + 20 + 16 + 6 + 5 + 10.)
2026-10-20 (banners/coupons/complaints async harness migration)
apps/admin-ui/tests/pages/banners.test.tsx
- renderBanners -> await renderAndFlush; error row awaits findByText; mutation
rows waitFor the recorded mutation / alert instead of fixed flushes.
- ABANUI-19 uses a stateful getBanners/updateBanner impl so the real refetch
reflects the saved serialNum before the empty-slot step.
apps/admin-ui/tests/pages/banner-create.test.tsx
- dropped the global.fetch spy (it swallowed the tRPC network mock); file://
blob + upload PUT now go through setRawFetchHandler; create rows waitFor
the mutation/alert.
apps/admin-ui/tests/pages/banner-edit.test.tsx
- renderEdit -> await renderAndFlush; prefill rows await the banner query;
save rows waitFor the mutation / alert before pressing alert buttons.
apps/admin-ui/tests/pages/complaints.test.tsx
- removed the local trpc-client jest.mock; real infinite query + real
refetch/fetchNextPage. Retry/focus/resolve assertions observe
procedureQueryCalls; ACOMPUI-13 uses an impl that serves page 2 on cursor.
apps/admin-ui/tests/pages/coupons.test.tsx
- renderCoupons -> await renderAndFlush; reserved tabs await the real query;
delete rows waitFor mutation/alert; ACOUPUI-03 expects the retry request.
apps/admin-ui/tests/pages/coupon-create.test.tsx
- unchanged (already async-safe; passes on the real client).
apps/admin-ui/tests/pages/coupon-edit.test.tsx
- renderEdit -> await renderAndFlush; prefill/save rows await query and
waitFor mutation/invalidation/alert.
No application source, harness or row ids changed.
2026-10-20 10:45:28 IST (products/tags/groupings async harness migration)
apps/admin-ui/tests/pages/products.test.tsx
- renderProducts -> await renderAndFlush; every row async; error row stays
synchronous after the flushed render; pull-to-refresh/focus rows await act.
apps/admin-ui/tests/pages/product-add.test.tsx
- renderAdd -> await renderAndFlush (+flush); dropped the global.fetch
override that swallowed the tRPC network mock in favour of
setRawFetchHandler for the file:// blob + upload PUT; create rows await a
`createdPayload()` waitFor instead of asserting before the mutation lands.
apps/admin-ui/tests/pages/product-edit.test.tsx
- renderEdit -> await renderAndFlush (+flush); uploads via setRawFetchHandler;
update rows await `updatedPayload()`; refresh-event row awaits the flush.
apps/admin-ui/tests/pages/product-detail.test.tsx
- renderDetail -> await renderAndFlush (+flush); uploads via
setRawFetchHandler; not-found row uses findByText; response rows await
`responsePayload()` + waitFor on the invalidation.
apps/admin-ui/tests/pages/popular-items.test.tsx
- "Choose products..." press now flushes the real getAllSkusSummary query
before asserting the selector options / query call count.
apps/admin-ui/tests/pages/prices-overview.test.tsx
- renderPrices -> await renderAndFlush; pressSave awaits flush; all rows async.
apps/admin-ui/tests/pages/product-tags.test.tsx
- renderTags -> await renderAndFlush; error row uses findByText.
apps/admin-ui/tests/pages/product-tag-add.test.tsx
- renderAdd -> await renderAndFlush; image upload forced through
setRawFetchHandler instead of replacing global.fetch.
apps/admin-ui/tests/pages/product-tag-edit.test.tsx
- renderEdit -> await renderAndFlush (+flush for the sku-summary prefill);
image upload via setRawFetchHandler.
apps/admin-ui/tests/pages/product-tag-order.test.tsx
- renderOrder -> await renderAndFlush; error row uses findByText.
apps/admin-ui/tests/pages/product-groupings.test.tsx
- renderGroups -> await renderAndFlush; error row findByText; refresh-event
row awaits the flush.
apps/admin-ui/tests/pages/product-grouping-create.test.tsx
- renderCreate -> await renderAndFlush.
apps/admin-ui/tests/pages/product-grouping-edit.test.tsx
- renderEdit -> await renderAndFlush (+flush for ProductGroupForm skus).
No application source, harness, assertion strength or row ids changed.
2026-10-20 10:45:51 admin-ui tests: adapt six suites to the "real trpc client + real React Query" harness
(only global.fetch is mocked). Tests only - no app source, harness, assertion intent or row id changed.
apps/admin-ui/tests/app/drawer-layout.test.tsx
- ADRAW-03/05/06: await view.findByText(...) for the `admin.staffUser.me` payload instead of
reading it synchronously after flush (the query resolves a tick later on the real client).
apps/admin-ui/tests/pages/dashboard.test.tsx
- ADASH-02: await view.findByText('7') for the essentials badge.
- ADASH-03: flush before queryByText('0') so the zero-badge assertion is not vacuous.
apps/admin-ui/tests/pages/login.test.tsx
- ALOGIN-09: server error is now `new Error('')` (a real Error with an empty message) so the
real TRPCClientError carries an empty message and the page's "Login failed" fallback renders.
- ALOGIN-05/06: waitFor the recorded login mutation input instead of a fixed flush count.
apps/admin-ui/tests/pages/customize-app.test.tsx
- bound/region rows await findByText/findByDisplayValue for the bounds -> selectedBoundId ->
getBoundSettings cascade; save rows waitFor the mutation input and the Alert.
- ACUST-05/25: waitFor the bound-settings query inputs / both mutation payloads.
- ACUST-01: seeds the `admin.region.current` cache entry on a test query client. The real
httpBatchLink puts region.current + bounds + regionConstants in ONE request, so `mode:'pending'`
on bounds also stalls region.current; seeding keeps the header assertion while bounds loads.
apps/admin-ui/tests/pages/send-notifications.test.tsx
- renderPage is async (render + flush) so the users query resolves before the form is queried;
all rows await it (ANOTIF-01 still asserts the pending "Loading users..." state).
- new openDropdown helper; send rows waitFor the recorded mutation input / alerts.
- ANOTIF-11: dropped fake timers (they froze the batch/timer chain); waits up to 4s for the
dropdown's real 2s debounce to produce the `search:'987'` query.
apps/admin-ui/tests/lib/upload-hook.test.tsx
- Probe now renders inside renderWithProviders (real trpc.Provider + QueryClient) - the hook's
generateUploadUrls.useMutation needs the tRPC context.
- presigned PUTs are stubbed with setRawFetchHandler (replacing global.fetch killed the tRPC
network mock); assertions read the raw handler's jest.Mock calls instead of global.fetch.
2026-10-20 (infinite-query fixture shape)
apps/admin-ui/tests/pages/coupons.test.tsx
- paginated()/page() now returns ONE page ({coupons,count,nextCursor}) because
the real useInfiniteQuery builds `pages` itself (was {pages:[…],pageParams}).
- query-input assertions include the client-generated direction:'forward';
ACOUPUI-05 asserts the unfiltered query was issued (cache hit on reset).
apps/admin-ui/tests/pages/complaints.test.tsx
- setComplaintPage() returns a single page; ACOMPUI-13 serves page 2 via an
impl keyed on input.cursor and asserts the cursor request + appended row.
2026-10-20 10:52:10 IST (follow-up: stabilise alert assertions under parallel runs)
apps/admin-ui/tests/pages/product-add.test.tsx, product-edit.test.tsx,
product-detail.test.tsx, product-tag-add.test.tsx, product-tag-edit.test.tsx,
prices-overview.test.tsx, popular-items.test.tsx, product-grouping-create.test.tsx
- post-mutation `expect(alertSpy).toHaveBeenCalledWith(...)` assertions now run
inside `await waitFor(...)` (same expected args, no weakened matchers) so the
success/error alert is observed after the real React Query mutation settles.
No application source, harness, assertion strength or row ids changed.
2026-10-20 10:49:48 IST (tests: real tRPC client + real React Query harness)
apps/admin-ui/tests/pages/user-management.test.tsx
- removed the local jest.mock('../mocks/trpc-client') proxy; the page now uses the real
useInfiniteQuery. setUsersPages feeds one page per cursor via an `impl` keyed on input.cursor.
- AUM-02/AUM-07/AUM-13: refetch assertions replaced with recorded query-call counts
(the fake __refetch/__fetchNextPage spies no longer exist).
- AUM-11/AUM-12 trigger onEndReached and assert the cursor request; AUM-14 sets mode:'pending'
after page 1 so the real isFetchingNextPage drives the footer spinner.
- AUM-10/AUM-17 expect the client-added direction:'forward' in the query input.
apps/admin-ui/tests/pages/user-detail.test.tsx
- removed the local jest.mock proxy; AUD-02/AUD-07 assert a new getUserDetails request
(query-call count) instead of the fake refetch spy; AUD-10 awaits findByText for the
incidents query.
apps/admin-ui/tests/pages/stores.test.tsx
- renderStores is async (renderAndFlush); every data row awaits it. ASTOREUI-01 keeps the
synchronous loading assertion via renderWithProviders. ASTOREUI-14 de-dupes the recorded
focus callbacks (re-renders push the same callback again).
apps/admin-ui/tests/pages/store-add.test.tsx
- global.fetch replacement removed in favour of setRawFetchHandler (file:// reads + PUTs).
- ASTOREADD-07 asserts the exact payload (no imageUrl key) because JSON drops undefined.
apps/admin-ui/tests/pages/store-edit.test.tsx
- async render (renderAndFlush + flush) so getStoreById and the ProductsSelector SKU query
resolve; mutations waitFor the recorded input. setRawFetchHandler for uploads.
- ASTOREEDIT-05 asserts imageUrl is absent from the JSON payload.
apps/admin-ui/tests/pages/vendor-snippets.test.tsx
- renderPage is async; all rows await the getAll query. Form rows flush after opening the
form so its SKU list loads. Mutation/refetch/orders rows waitFor the recorded state.
apps/admin-ui/tests/components/coupon-form.test.tsx
- openUsersWith marks the cached user query stale (invalidateQueries) before reopening so the
real React Query refetches; product rows flush before opening the selector.
apps/admin-ui/tests/components/product-form.test.tsx
- APFORM-14/16/17 flush before reading SKU/store options.
apps/admin-ui/tests/components/product-group-form.test.tsx
- AGRPF-04 flushes before asserting the SKU labels.
apps/admin-ui/tests/components/slot-form.test.tsx
- ASLOTF-04/05/08 and AVSF-06/07 flush before selecting SKUs/groups.
apps/admin-ui/tests/components/store-form.test.tsx
- setRawFetchHandler for uploads; ASTOREF-05 waits for the upload; ASTOREF-08 flushes for the
preselected SKUs.
apps/admin-ui/tests/components/tag-form.test.tsx
- ATAGF-06 flushes the SKU query before selecting a product.
apps/admin-ui/tests/components/user-incidents-view.test.tsx
- removed the local jest.mock proxy; AINC-06/AUIV-02 assert a new getUserIncidents request
after the mutation instead of the fake refetch spy.
apps/admin-ui/tests/components/vendor-snippet-form.test.tsx
- renders through renderWithProviders (was bare render, no tRPC/React Query context);
product/slot rows flush before interacting.
No application source or harness file was modified; all row ids kept.
================================================================================
[2026-10-20 09:15:00 IST] FIX-2026-10-20-11 real-client migration stabilisation
================================================================================
Full migration to real tRPC client + real React Query with a network-level mock is
complete for both apps. Final verification:
user-ui 1142/1142 tests, 51/51 suites, 3 consecutive full runs green
admin-ui 819/819 tests, 64/64 suites, 3 consecutive full runs green
both apps: test:typecheck clean
Final diffs (on top of the per-suite migrations already logged above):
- tests/setup.ts (both apps): @testing-library/react-native configure({ asyncUtilTimeout: 5000 }).
The 1s default was too tight once every query/mutation settles through the real client
under the full parallel suite.
- tests/helpers/test-utils.tsx (both apps): pass `children` inside the trpc.Provider props
(React.createElement overload requires it) — typecheck fix, same rendered tree.
- tests/mocks/trpc-client.ts (both apps): record the batch calls BEFORE the `mode: 'pending'`
short-circuit, so "exactly one request was made" still holds while a hook is loading.
- user-ui tests/components/complaint-form.test.tsx: CF-03/CF-04 waitFor the success alert and
onClose (the request is recorded before the mutation's onSuccess runs).
- user-ui tests/pages/coupons.test.tsx: COUPON-17 uses waitFor instead of flush(1).
- user-ui tests/lib/prominent-api-hooks.test.tsx: API-18 waits for the hook data after the
region switch (not just the CDN request).
- user-ui tests/pages/home.test.tsx: HOME-95 now pins the behaviour under the real client
(stale slot reconciled to 1849; quantity 2 -> 4 from the remove+add pair).
- admin-ui tests/pages/banner-edit.test.tsx: ABANE-03 awaits the ProductsSelector SKU label.
No application source changed.

View file

@ -1,194 +0,0 @@
diff --git a/apps/admin-ui/app/(drawer)/dashboard/products/add.tsx b/apps/admin-ui/app/(drawer)/dashboard/products/add.tsx
index e227458..4465099 100644
--- a/apps/admin-ui/app/(drawer)/dashboard/products/add.tsx
+++ b/apps/admin-ui/app/(drawer)/dashboard/products/add.tsx
@@ -5,6 +5,15 @@ import ProductForm from '@/src/components/ProductForm'
import { trpc } from '@/src/trpc-client'
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore'
+// SKUs store bucket-relative object keys, not URLs. Drop the query string and
+// keep the last two path segments:
+// https://<acct>.r2.cloudflarestorage.com/meatfarmer-dev/product-images/1.jpg?X-Amz-...
+// -> product-images/1.jpg
+const toImageKey = (url: string): string => {
+ const parts = url.split('?')[0].split('/').filter(Boolean)
+ return parts.slice(-2).join('/')
+}
+
export default function AddProduct() {
const createProduct = trpc.admin.product.createProduct.useMutation()
const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
@@ -63,7 +72,8 @@ export default function AddProduct() {
let urlCursor = 0
const skus = values.variants.map((variant: any, vIndex: number) => {
const count = imageCounts[vIndex]
- const variantUrls = allUploadUrls.slice(urlCursor, urlCursor + count)
+ // Send keys, not the presigned URLs.
+ const variantUrls = allUploadUrls.slice(urlCursor, urlCursor + count).map(toImageKey)
urlCursor += count
return {
diff --git a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx
index ac72345..69f0c97 100644
--- a/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx
+++ b/apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx
@@ -6,6 +6,15 @@ import ProductForm, { ProductFormRef } from '@/src/components/ProductForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';
+// SKUs store bucket-relative object keys, not URLs. Drop the query string and
+// keep the last two path segments:
+// https://<acct>.r2.cloudflarestorage.com/meatfarmer-dev/product-images/1.jpg?X-Amz-...
+// -> product-images/1.jpg
+const toImageKey = (url: string): string => {
+ const parts = url.split('?')[0].split('/').filter(Boolean)
+ return parts.slice(-2).join('/')
+}
+
export default function EditProduct() {
const { id } = useLocalSearchParams();
const productId = Number(id);
@@ -140,9 +149,10 @@ export default function EditProduct() {
// Existing images (mimeType === null) stay as-is
const existingUrls = variantImages[vIndex]
?.filter((img) => img.mimeType === null)
- .map((img) => img.url) || []
+ .map((img) => toImageKey(img.url)) || []
- const allUrls = [...existingUrls, ...newUrls]
+ // Send keys, not URLs — the SKU stores the bucket-relative object key.
+ const allUrls = [...existingUrls, ...newUrls.map(toImageKey)]
return {
id: variant.id,
diff --git a/apps/admin-ui/hooks/useUploadToObjectStore.ts b/apps/admin-ui/hooks/useUploadToObjectStore.ts
index 8327cfa..25c8ee7 100644
--- a/apps/admin-ui/hooks/useUploadToObjectStore.ts
+++ b/apps/admin-ui/hooks/useUploadToObjectStore.ts
@@ -43,9 +43,11 @@ export function useUploadToObjectStorage() {
headers: { 'Content-Type': mimeType },
});
- if (!response.ok) {
- throw new Error(`Upload ${index + 1} failed with status ${response.status}`);
- }
+ if (!response.ok) {
+ const body = await response.text(); // <Error><Code>…</Code></Error>
+ console.error('upload failed', response.status, body);
+ throw new Error(`Upload ${index + 1} failed with status ${response.status}`);
+ }
// Update progress
setProgress(prev => prev ? { ...prev, completed: prev.completed + 1 } : null);
diff --git a/apps/backend/src/lib/s3-client.ts b/apps/backend/src/lib/s3-client.ts
index 1f8b437..47372ca 100644
--- a/apps/backend/src/lib/s3-client.ts
+++ b/apps/backend/src/lib/s3-client.ts
@@ -118,10 +118,14 @@ export async function generateSignedUrlFromS3Url(s3UrlRaw: string|null, expiresI
try {
const client = getAwsClient()
- const url = buildObjectUrl(getS3BucketName(), s3Url)
- const signedRequest = await client.sign(url, {
+ // X-Amz-Expires must be a QUERY param, not a header: with signQuery, aws4fetch
+ // hoists header values into the query but still lists them in
+ // X-Amz-SignedHeaders, and R2 then hashes the missing header as empty — which
+ // makes the signature mismatch (S3 tolerates it, R2 does not).
+ const url = new URL(buildObjectUrl(getS3BucketName(), s3Url))
+ url.searchParams.set('X-Amz-Expires', String(expiresIn))
+ const signedRequest = await client.sign(url.toString(), {
method: 'GET',
- headers: { 'X-Amz-Expires': String(expiresIn) },
aws: { signQuery: true },
})
return signedRequest.url
@@ -170,13 +174,13 @@ export async function generateUploadUrl(key: string, mimeType: string, expiresIn
await createUploadUrlStatus(key)
const client = getAwsClient()
- const url = buildObjectUrl(getS3BucketName(), key)
- const signedRequest = await client.sign(url, {
+ // Same as the GET path above: keep X-Amz-Expires in the query, and do not
+ // sign Content-Type — leaving it unsigned means the client may send any value
+ // without breaking the signature.
+ const url = new URL(buildObjectUrl(getS3BucketName(), key))
+ url.searchParams.set('X-Amz-Expires', String(expiresIn))
+ const signedRequest = await client.sign(url.toString(), {
method: 'PUT',
- headers: {
- 'Content-Type': mimeType,
- 'X-Amz-Expires': String(expiresIn),
- },
aws: { signQuery: true },
})
@@ -193,15 +197,22 @@ export async function generateUploadUrl(key: string, mimeType: string, expiresIn
// return decodeURIComponent(rawKey);
// }
-// New function (excludes bucket name)
+/**
+ * Normalise an image reference to the bucket-relative object key that SKUs store.
+ *
+ * Accepts either a full (presigned) URL or an already-extracted key, so callers
+ * can send whichever they have. Drops the query string, then keeps the last two
+ * path segments:
+ *
+ * https://<account>.r2.cloudflarestorage.com/meatfarmer-dev/product-images/1.jpg?X-Amz-...
+ * -> product-images/1.jpg
+ * product-images/1.jpg
+ * -> product-images/1.jpg
+ */
export function extractKeyFromPresignedUrl(url: string): string {
- const u = new URL(url)
- const rawKey = u.pathname.replace(/^\/+/, '') // remove leading slash
- const decodedKey = decodeURIComponent(rawKey)
- // Remove bucket prefix
- const parts = decodedKey.split('/')
- parts.shift() // Remove bucket name
- return parts.join('/')
+ const withoutQuery = url.split('?')[0]
+ const parts = withoutQuery.split('/').filter(Boolean)
+ return decodeURIComponent(parts.slice(-2).join('/'))
}
export async function claimUploadUrl(url: string): Promise<void> {
diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/product.ts b/apps/backend/src/trpc/apis/admin-apis/apis/product.ts
index 7018961..57b51a7 100644
--- a/apps/backend/src/trpc/apis/admin-apis/apis/product.ts
+++ b/apps/backend/src/trpc/apis/admin-apis/apis/product.ts
@@ -260,8 +260,6 @@ export const productRouter = router({
await deleteImageUtil({ keys: deletedImageKeys })
}
- const allUploadUrls: string[] = skus.flatMap((sku) => sku.images)
-
const skuInputs = skus.map((sku) => ({
id: sku.id,
name: sku.name ?? null,
diff --git a/packages/ui/src/components/ImageUploaderNeo.tsx b/packages/ui/src/components/ImageUploaderNeo.tsx
index eb5e5d7..37201f9 100644
--- a/packages/ui/src/components/ImageUploaderNeo.tsx
+++ b/packages/ui/src/components/ImageUploaderNeo.tsx
@@ -11,11 +11,12 @@ import usePickImage from './use-pick-image'
export type { ImageUploaderNeoItem, ImageUploaderNeoPayload } from '@packages/shared'
-const ImageUploaderNeo: React.FC<ImageUploaderNeoProps> = ({
+const ImageUploaderNeo: React.FC<ImageUploaderNeoProps & { testID?: string }> = ({
images,
onImageAdd,
onImageRemove,
allowMultiple = true,
+ testID,
}) => {
const totalImageCount = images.length
@@ -60,6 +61,7 @@ const ImageUploaderNeo: React.FC<ImageUploaderNeoProps> = ({
</View>
))}
<MyTouchableOpacity
+ testID={testID}
disabled={!allowMultiple && totalImageCount >= 1}
onPress={handlePickImage}
style={tw`w-1/3 px-1 mb-2`}

View file