9 KiB
user-ui test suite
Runnable implementation of the cases catalogued in
../JEST-TEST-CASES.md.
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
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(<Home />, { auth: 'in' })
expect(getByText('Loading products...')).toBeTruthy()
})
})
Rules:
- One
it()per catalogue row, prefixed with the row id (HOME-01: ...). resetAllMocks()inbeforeEach.- Assert the procedure + exact input for every mutation
(
lastProcedureInput('user.order.placeOrder')). - Prefer
getByTestId/queryByTestIdover text matching. If a component is missing a testID, add only thetestIDattribute to the component (never change behaviour) and report it. Every added id is recorded inchange-log.txt. - 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, with tags and a loaded (isLoading: false) catalogue state |
seedEmptyCatalogue() |
clears the central product store — a cold start, for first-load loading/error cases |
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')` |
Catalogue coupon prices are seeded through the store, never through a request:
useCentralProductStore.getState().setCouponOffers({ [skuId]: [offer] }).
seedBoot() seeds a catalogue without offers, so the default everywhere is "no
coupon price".
Catalogue pages render from useCentralProductStore, not from their own
useAllProducts() call. renderWithProviders(ui, { withProductStore: true })
mounts the real producer, so the mocked products JSON still drives what the page
shows (loading, error, tags and payload overrides included).
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
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
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
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:
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
useGetCartreadscart_itemsfrom storage and enriches from the central stores, so seed both (seedCentralStores()+__set('cart_items', …)).- Auth seeding must be a decodable JWT (
TEST_JWT), becausegetCurrentUserIddecodes the token to derive the user id. useRegionkeeps 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 withjest.isolateModules.- The
expo-routermock 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.tsno longer replaces the client module. It exports the procedure registry (setProcedure, defaults, call recording) andinstallTrpcNetworkMock(), whichtests/setup.tsinstalls onglobal.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. renderWithProviderswraps withQueryClientProviderand the realtrpc.Provider.lastProcedureInput/procedureMutationCallsare filled from the real requests.useUtils().x.invalidate()is real; the test QueryClient records the query keys soprocedureInvalidations(path)still works.
Assertions are asynchronous
Queries resolve after a tick and mutations settle asynchronously. Prefer:
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.