# user-ui test suite Runnable implementation of the cases catalogued in [`../JEST-TEST-CASES.md`](../JEST-TEST-CASES.md). ```bash cd apps/user-ui bun run test -- tests/pages/home.test.tsx # a single file bun run test # everything ``` Runner: `jest-expo` + `@testing-library/react-native`. Application code (stores, hooks, components) runs for real; only network and native modules are mocked. --- ## Layout ``` tests/ jest.config.js preset, aliases, native-module mocks setup.ts globals (fetch, console, act env) fixtures/index.ts backend-shaped fixtures + cache URL builders helpers/ test-utils.tsx render helpers, seeding helpers reset.ts resetAllMocks() for beforeEach mocks/ trpc-client.ts procedure-registry mock (queries + mutations + utils) trpc-defaults.ts default payload per procedure fetch-json.ts URL-keyed CDN JSON mock expo-router-mock.tsx recorded router + layout primitives secure-store-mock.ts in-memory SecureStore (StorageService*) expo-location-mock.ts configurable device location expo-notifications-mock.ts configurable push + listener emitters auth-context.tsx deterministic AuthContext replacement native/* native-module shims ``` ## Standard test shape ```tsx import { waitFor, fireEvent } from '@testing-library/react-native' import Home from '@/app/(drawer)/(tabs)/home/index' import { renderWithProviders, seedBoot, flush } from '../../helpers/test-utils' import { resetAllMocks } from '../../helpers/reset' import { setProcedure, lastProcedureInput } from '../../mocks/trpc-client' describe('Home', () => { beforeEach(() => resetAllMocks()) it('HOME-01: shows the loading copy while products are pending', async () => { seedBoot() setProcedure('common.essentialConsts', { mode: 'pending' }) const { getByText } = renderWithProviders(, { auth: 'in' }) expect(getByText('Loading products...')).toBeTruthy() }) }) ``` Rules: 1. One `it()` per catalogue row, prefixed with the row id (`HOME-01: ...`). 2. `resetAllMocks()` in `beforeEach`. 3. Assert the procedure + exact input for every mutation (`lastProcedureInput('user.order.placeOrder')`). 4. Prefer `getByTestId` / `queryByTestId` over text matching. If a component is missing a testID, **add only the `testID` attribute** to the component (never change behaviour) and report it. Every added id is recorded in `change-log.txt`. 5. Fake timers only for debounce / countdown / modal-delay cases. ## Render helpers | Helper | Purpose | | --- | --- | | `renderWithProviders(ui, opts)` | QueryClient + RefreshProvider + real `AuthProvider` | | `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 `AuthProvider`, for trees that only use `useAuthOptional`), `queryClient`, `withRefresh`, `userId`, `token`. ## Seeding | Helper | Effect | | --- | --- | | `seedJsonCache(overrides)` | products/availability/slots/stores/store-detail CDN docs | | `seedCentralStores(overrides)` | central product + slot stores (needed by `useGetCart`) | | `seedRegion(region, boundId)` | selects the browsing region without the location flow | | `seedSelectedAddress(id)` | sets `addressStore.selectedAddressId` | | `seedBoot({auth,addressId})` | the usual home/cart boot state | | `seedAuthStorage('in' | 'out')` | token/userId in the storage mock | Storage: `import { __set, __delete, __snapshot } from '../../mocks/secure-store-mock'`. Cart lines live under `cart_items` / `flash_cart_items` (`CART_REG`, `CART_FLASH`). ## Procedure mock ```ts setProcedure('user.order.getOrders', { data: { data: [], pagination: { totalPages: 0 } } }) setProcedure('user.auth.sendOtp', { mode: 'error', error: new Error('boom') }) setProcedure('user.auth.sendOtp', { mode: 'pending' }) setProcedure('user.order.placeOrder', { impl: (input) => ({ data: { orders: [input] } }) }) lastProcedureInput('user.auth.sendOtp') procedureMutationCalls('user.order.placeOrder') procedureQueryCalls('user.order.getOrders') trpc.useUtils() // invalidations are recorded as jest.fn()s ``` Defaults for every procedure live in `mocks/trpc-defaults.ts`. ## CDN JSON mock ```ts import { setJsonResponse, setJsonError, setJsonPending, jsonCallsFor } from '../../mocks/fetch-json' import { productsCacheUrl } from '../../fixtures' setJsonResponse(productsCacheUrl(), { products: [], count: 0, tags: [] }) setJsonError(productsCacheUrl(), new Error('offline')) ``` `setJsonResponse` supports a string, RegExp or predicate matcher; the last registration wins. ## Native modules ```ts import { __configure as configureLocation } from '../../mocks/expo-location-mock' configureLocation({ permission: 'denied', position: null }) import { __configure as configureNotifications, __emitNotification, __emitResponse } from '../../mocks/expo-notifications-mock' import { router, __setParams, __resetRouterMock } from '../../mocks/expo-router-mock' expect(router.push).toHaveBeenCalledWith('/home/slot-view?slotId=1849') ``` For deterministic auth states, mock the context at the top of the file: ```tsx jest.mock('@/src/contexts/AuthContext', () => require('../../mocks/auth-context')) import { __setAuthState } from '../../mocks/auth-context' __setAuthState({ isAuthenticated: true, isLoading: false, user: AUTH_USER }) ``` ## Fixtures `CONSTS`, `CONSTS_FLASH_OFF`, `PRODUCTS`, `MERGED_PRODUCTS`, `TAGS`, `AVAILABILITY`, `SLOTS` (+ `makeSlots(now)`), `STORES`, `STORE_DETAIL_1`, `CART_REG`, `CART_FLASH`, `ADDRESSES` (`A1`/`A2`/`A3`), `COUPONS` (`C1…C8`), `ORDERS` (`O1…O6`), `COMPLAINTS`, `REVIEWS`, `PRODUCT_DETAILS`, `AUTH_USER`, `TEST_JWT`, `REGION_1`, `REGION_2`, `BOUND_1`, and the URL builders `productsCacheUrl` / `availabilityCacheUrl` / `slotsCacheUrl` / `storesCacheUrl` / `storeDetailCacheUrl`. ## Known harness behaviours - `useGetCart` reads `cart_items` from storage and enriches from the central stores, so seed both (`seedCentralStores()` + `__set('cart_items', …)`). - Auth seeding must be a decodable JWT (`TEST_JWT`), because `getCurrentUserId` decodes the token to derive the user id. - `useRegion` keeps module-level startup state. In a single file, tests that assert the startup adopt/switch path should be ordered first, or the file should re-require the module with `jest.isolateModules`. - The `expo-router` mock records navigation but never navigates; layout 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(, { 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.