# admin-ui test suite Runnable implementation of the cases catalogued in [`../JEST-TEST-CASES.md`](../JEST-TEST-CASES.md). ```bash cd apps/admin-ui bun run test -- tests/pages/dashboard.test.tsx # a single file bun run test # everything bun run test:typecheck # tsc over the app + tests ``` Runner: `jest-expo` + `@testing-library/react-native`. Application code (pages, hooks, components, auth context) runs for real; only the tRPC client and native modules are mocked. React Query is real, but the tRPC mock replaces the hooks, so queries resolve synchronously from the procedure registry. --- ## Layout ``` tests/ jest.config.js preset, aliases, native-module mocks setup.ts globals (fetch, console, act env) fixtures/index.ts backend-shaped fixtures helpers/ test-utils.tsx render helpers + auth seeding reset.ts resetAllMocks() for beforeEach mocks/ trpc-client.ts procedure-registry mock (queries + mutations + utils) trpc-defaults.ts default payload per procedure staff-auth-context.tsx deterministic StaffAuthContext replacement expo-router-mock.tsx recorded router + layout primitives secure-store-mock.ts in-memory SecureStore expo-notifications-mock.ts native/* native-module shims ``` ## Standard test shape ```tsx import React from 'react' import { fireEvent } from '@testing-library/react-native' import Products from '@/app/(drawer)/dashboard/products/index' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { setProcedure, lastMutationInput } from '../mocks/trpc-client' import { router } from '../mocks/expo-router-mock' describe('Products', () => { beforeEach(() => resetAllMocks()) it('APLIST-01: shows the loading copy', () => { setProcedure('admin.product.getProducts', { mode: 'pending' }) const view = renderWithProviders(, { auth: 'in' }) expect(view.getByText('Loading products...')).toBeTruthy() }) }) ``` Rules: 1. One `it()` per catalogue row, prefixed with the row id (`APLIST-01: ...`). 2. `resetAllMocks()` in `beforeEach`. 3. Assert the procedure + exact input for every mutation (`lastMutationInput('admin.product.createProduct')`). 4. Prefer `getByTestId` / `queryByTestId` over text matching, but text matching is fine for the catalogue's visible-copy assertions. If a component is missing a testID, **add only the `testID` attribute** (never change behaviour) and report it. 5. `act(...)` warnings are noisy but non-fatal. Use `await flush()` / `waitFor` after mutations and async effects. ## Render helpers | Helper | Purpose | | --- | --- | | `renderWithProviders(ui, opts)` | QueryClient + `trpc.Provider` + `RefreshProvider` + real `StaffAuthProvider` | | `renderAndFlush(ui, opts)` | same, then `await flush()` | | `flush(times = 1)` | drain microtasks/macrotasks inside `act` | | `createTestQueryClient()` | fresh client (retry off, infinite gc) | `opts`: `auth` = `'in' | 'out' | false` (default `'out'`; `false` skips both the auth seeding and the auth provider), `queryClient`, `withRefresh`, `withAuth`. `auth: 'in'` writes `jwt_token` + `staff_session` to the storage mock so the real `StaffAuthProvider` boots signed in after a flush. ## Seeding / resetting ```ts import { __set, __delete, __snapshot } from '../mocks/secure-store-mock' __set('jwt_token', TEST_JWT) __set('staff_session', JSON.stringify(STAFF)) ``` ## Procedure mock ```ts setProcedure('admin.product.getProducts', { data: PRODUCTS_RESPONSE }) setProcedure('admin.product.getProducts', { mode: 'error', error: new Error('boom') }) setProcedure('admin.product.getProducts', { mode: 'pending' }) setProcedure('admin.product.createProduct', { impl: (input) => ({ product: input }) }) lastMutationInput('admin.product.createProduct') // exact input of the last call lastProcedureInput('admin.coupon.getAll') // query or mutation procedureMutationCalls('admin.coupon.create') // all inputs procedureQueryCalls('admin.coupon.getAll') trpc.useUtils() // invalidations recorded as jest.fn()s ``` Defaults for every procedure live in `mocks/trpc-defaults.ts`. ## Deterministic auth For exact signed-in / loading states without the provider's async bootstrap: ```tsx jest.mock('@/components/context/staff-auth-context', () => require('../../mocks/staff-auth-context')) import { __setStaffState } from '../../mocks/staff-auth-context' __setStaffState({ isLoggedIn: true, isLoading: false, staff: STAFF }) ``` `renderWithProviders(..., { auth: false })` skips both seeding and the provider; the mocked `useStaffAuth` still supplies the state above. ## Navigation ```ts import { router, __setParams } from '../mocks/expo-router-mock' __setParams({ id: '21' }) expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit') ``` `boom`/`expo-router` layouts render their children, so route files can be mounted directly. ## Fixtures `STAFF`, `STAFF_NO_REGION`, `REGION`, `BOUNDS`, `BOUND_SETTINGS`, `REGION_CONSTANTS`, `STORE_1`, `STORE_GLOBAL`, `STORES`, `P_CHICKEN`, `P_CUCUMBER`, `P_GLOBAL`, `P_OUT`, `P_NO_IMAGE`, `P_PARTIAL`, `PRODUCTS`, `PRODUCTS_RESPONSE`, `SKUS_SUMMARY`, `SLOT_1`, `SLOT_FULL`, `SLOT_INACTIVE`, `SLOTS`, `SLOT_DETAIL`, `ORDER_1`, `ORDER_FLASH`, `ORDER_DELIVERED`, `ORDER_CANCELLED`, `ORDER_NEGATIVE`, `ORDERS`, `ORDERS_RESPONSE`, `ORDER_DETAILS`, `SLOT_ORDERS`, `USER_1`, `USER_SUSPENDED`, `USER_NO_NAME`, `USERS`, `USER_DETAILS`, `USER_INCIDENTS`, `NOTIFICATION_USERS`, `COUPON_1`, `COUPON_GLOBAL`, `COUPON_EXPIRED`, `COUPON_INVALIDATED`, `COUPON_RESERVED`, `COUPONS`, `TAG_1`, `TAG_2`, `TAGS`, `GROUP_1`, `GROUPS`, `BANNER_1`, `BANNERS`, `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(, { 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.