Mobile development · Intermediate · 35 min
Test the Larkfield app with Jest and React Native Testing Library
By Padding · Updated 18 Nov 2026
Expo SDK 58 · jest-expo 58.0 · Jest 30.5 · React Native Testing Library 14.1 · Node.js 26 (node:26 image)
You will have one Jest suite for the Larkfield Expo app that fakes only the native modules and the network, tests screens by role and label, opens routes by URL, controls the clock and retry timer, enforces coverage floors for the data and sync code and runs on every pull request.
On this page
Six parts in, the Larkfield app has 14 test files, but each part added its own: part 1 checks the route tree, part 2 the phone rules, the booking schema and the form, part 3 the SQL, part 4 the sync against the mock clinic API, part 5 the reminder plan, the permission prompt and push registration, part 6 the link rewrite. Every file mocks native modules in its own way, part 1's route test stopped matching the app when part 3 put a database in the root layout, nothing tests the SQLite-backed screens the way a patient uses them, the reminder tests pass a hand-made now around, and nothing runs the suite when someone opens a pull request.
This part turns those files into one suite you can rely on. You move the Jest settings into one file, replace the three native modules the app depends on (expo-sqlite, expo-notifications and NetInfo) in one setup file so a new test needs no mock lines of its own, test the Appointments tab by role and label the way a screen reader finds things, bring part 1's route test up to date with renderRouter, take control of the clock and the retry timer, set coverage floors for the data and sync code, and run it all on GitHub for every pull request.
The rule for mocks is the one this part keeps coming back to: replace only what cannot run on a computer, at the point where the app touches it. That means the native modules, and the network where a test needs to decide what the server answers. The SQL, the sync logic, the screens and the router stay real. A test that mocks the app's own modules mostly proves that the mocks agree with each other, which is why this part also rewrites part 5's prompt test, the one file in the series that does that.
Step 1 · Put the Jest settings in one file
Start in the project and check the four testing packages are the ones the series installed. jest-expo 58 needs Jest 30, and React Native Testing Library 14 renders through test-renderer, the replacement for the deprecated react-test-renderer:
cd ~/larkfield-app-demo
npm ls jest jest-expo @testing-library/react-native test-rendererSo far the Jest settings have lived in package.json as "jest": { "preset": "jest-expo" }. The suite now needs more than a preset, and Jest refuses to start when it finds settings in two places, so remove the package.json entry and give Jest a file of its own:
npm pkg delete jest
cat > jest.config.js <<'JS'
/** @type {import('jest').Config} */
module.exports = {
preset: 'jest-expo',
// Runs before each test file, after Jest itself is ready.
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
// Build output from `npx expo export` is never a test.
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/.expo/'],
// Forget recorded calls between tests, so one test cannot pass because of another.
clearMocks: true,
// The first render in a file loads React Native and can be slow, more so with coverage on.
testTimeout: 15_000,
}
JSclearMocks clears the calls a mock has recorded before every test, but keeps what the mock returns. That is the behaviour the shared mocks in the next step rely on. The default test timeout is 5 seconds; the first screen test in a file has to load React Native and the router, which on a shared CI machine with coverage switched on can take longer, so the limit is raised to 15.
The setup file is where native modules are replaced. Start with NetInfo. Its package ships an official Jest mock that reports a connected 3G phone, so use it instead of writing your own:
cat > jest.setup.ts <<'TS'
// Native modules that only exist on a phone are replaced here, once, for every test file.
// NetInfo's own Jest mock: fetch, addEventListener and useNetInfo are jest.fn() mocks.
jest.mock('@react-native-community/netinfo', () =>
require('@react-native-community/netinfo/jest/netinfo-mock.js'),
)
TS
npm pkg set scripts.test="jest" scripts.test:coverage="jest --coverage"Part 4's sync tests talk to the mock clinic API, so it has to be running whenever the whole suite runs. Start it in a second terminal from ~/larkfield-app-demo and leave it running:
node mock-api/server.mjsCheck it worked
List the files Jest will run, then run every folder except part 1's route test:
npx jest --listTests | sed "s#.*/larkfield-app-demo/##" | sort
npx jest --ci src/shared src/components src/db src/sync src/notifications src/linkingPart 1's src/__tests__/routes.test.tsx is left out of this run on purpose. Its renderRouter('./src/app') mounts the root layout, which since part 3 opens a database through expo-sqlite and since part 4 starts the outbox sync, and neither has a stand-in under Jest yet. The next step gives expo-sqlite one, and the renderRouter step brings the route test up to date.
The npm ls tree shows jest-expo@58.0.16, jest@30.5.2, @testing-library/react-native@14.1.0 and test-renderer@1.3.1, with no UNMET or invalid lines. The list shows the 14 test files from parts 1 to 6 and nothing from dist:
src/__tests__/routes.test.tsx(part 1)src/shared/phone.test.ts,src/shared/booking.test.tsandsrc/components/BookingForm.test.tsx(part 2)src/db/migrations.test.tsandsrc/db/appointments.test.ts(part 3)src/sync/backoff.test.tsandsrc/sync/sync-outbox.test.ts(part 4)reminders.test.ts,ReminderPrompt.test.tsx,permission.test.tsandpush.test.tsinsrc/notifications/__tests__(part 5)src/linking/rewrite.test.tsandsrc/linking/held-link.test.ts(part 6)
The run ends with Test Suites: 13 passed, 13 total and Tests: 63 passed, 63 total. If the sync suite fails with ECONNREFUSED 127.0.0.1:4010, the mock API is not running in the second terminal. If Jest says it found multiple configurations, the jest key is still in package.json.
Step 2 · Replace expo-sqlite and expo-notifications at the edge
Two more native modules need stand-ins. Write each one as a small module of its own, so every test file gets the same behaviour and you can read exactly what is fake.
expo-sqlite is the interesting one. Part 3 already has a real in-memory SQLite database for tests, openMemoryDb(), with the same methods as expo-sqlite's database. The fake only has to hand that database to the app through useSQLiteContext(), let SQLiteProvider render its children, and send the change events the Appointments tab listens for. The real library sends an event after each write when enableChangeListener is on; the fake does the same by watching the SQL that changes rows:
cat > src/db/testing/expo-sqlite-fake.ts <<'TS'
// For tests only: stands in for expo-sqlite, whose native database does not exist under Jest.
// Screens get part 3's in-memory database, so their SQL runs for real.
import type { ReactNode } from 'react'
import type { Db } from '../types'
type DatabaseChange = { databaseName: string; databaseFilePath: string; tableName: string; rowId: number }
type Listener = (event: DatabaseChange) => void
const WRITE = /^\s*(?:INSERT\s+INTO|UPDATE|DELETE\s+FROM)\s+(\w+)/i
const listeners = new Set<Listener>()
let current: Db | null = null
// Call this in each test before rendering. It returns the database the app will see.
export function setTestDatabase(db: Db): Db {
current = {
...db,
async runAsync(source, params) {
const result = await db.runAsync(source, params)
const tableName = WRITE.exec(source)?.[1]
if (tableName && result.changes > 0) {
const event = { databaseName: 'larkfield.db', databaseFilePath: ':memory:', tableName, rowId: result.lastInsertRowId }
for (const listener of [...listeners]) listener(event)
}
return result
},
}
return current
}
export function useSQLiteContext(): Db {
if (!current) throw new Error('Call setTestDatabase(db) before rendering a screen that uses the database')
return current
}
export function addDatabaseChangeListener(listener: Listener) {
listeners.add(listener)
return { remove: () => listeners.delete(listener) }
}
export function SQLiteProvider({ children }: { children: ReactNode }) {
return children
}
TSThe fake for expo-notifications records what the app asks the system to do. Every function is a jest.fn(), so a test can check the calls, and each returns what the real library returns in the simplest case: a granted permission, no pending tap, a scheduled identifier:
mkdir -p src/notifications/testing
cat > src/notifications/testing/expo-notifications-fake.ts <<'TS'
// For tests only: stands in for expo-notifications, which needs a phone's notification system.
export const SchedulableTriggerInputTypes = { DATE: 'date' } as const
export const AndroidImportance = { HIGH: 6 } as const
const granted = { status: 'granted', granted: true, canAskAgain: true }
export const scheduleNotificationAsync = jest.fn(
async (request: { identifier?: string }) => request.identifier ?? 'scheduled',
)
export const cancelScheduledNotificationAsync = jest.fn(async (_identifier: string) => undefined)
export const setNotificationChannelAsync = jest.fn(async () => null)
export const getPermissionsAsync = jest.fn(async () => granted)
export const requestPermissionsAsync = jest.fn(async () => granted)
export const setNotificationHandler = jest.fn()
export const getLastNotificationResponse = jest.fn(() => null)
export const clearLastNotificationResponse = jest.fn()
export const addNotificationResponseReceivedListener = jest.fn(() => ({ remove: jest.fn() }))
export const getExpoPushTokenAsync = jest.fn(async () => ({ type: 'expo', data: 'ExponentPushToken[test-device]' }))
TSNow register both in the setup file, next to NetInfo. A jest.mock call inside a test file still wins over these, which is why part 5's reminder, permission and push tests, which mock expo-notifications themselves, keep working unchanged. Their mocks replace the same native module and nothing of the app's, so they follow the rule; you can delete those blocks later and let the shared fake do the work:
cat > jest.setup.ts <<'TS'
// Native modules that only exist on a phone are replaced here, once, for every test file.
// Everything else (SQL, sync, screens, routing) runs for real.
// NetInfo's own Jest mock: fetch, addEventListener and useNetInfo are jest.fn() mocks.
jest.mock('@react-native-community/netinfo', () =>
require('@react-native-community/netinfo/jest/netinfo-mock.js'),
)
// expo-sqlite hands screens part 3's in-memory database (see src/db/testing/expo-sqlite-fake.ts).
jest.mock('expo-sqlite', () => require('./src/db/testing/expo-sqlite-fake'))
// expo-notifications records requests instead of showing anything.
jest.mock('expo-notifications', () => require('./src/notifications/testing/expo-notifications-fake'))
TSLast, one helper so screen tests do not each repeat the same set-up: a fresh in-memory database with every migration applied, already handed to the fake, and one sample appointment:
cat > src/db/testing/fixtures.ts <<'TS'
import type { NewAppointment } from '../appointments'
import { prepareDatabase } from '../migrations'
import type { Db } from '../types'
import { setTestDatabase } from './expo-sqlite-fake'
import { openMemoryDb } from './memory-db'
export const gpVisit: NewAppointment = {
serviceId: 'gp',
serviceName: 'GP consultation',
practitionerId: 'dr-kamau',
practitionerName: 'Dr Wanjiru Kamau',
startsAt: '2026-12-02T07:30:00.000Z',
patientName: 'Ngozi Adeyemi',
reason: 'Follow-up on blood pressure',
}
export async function openTestDatabase(): Promise<Db> {
const db = setTestDatabase(openMemoryDb())
await prepareDatabase(db)
return db
}
TSPart 5's ReminderPrompt.test.tsx is the one earlier file that breaks the rule. It mocks the app's own ../permission, ../push and ../reminders, so it proves the card calls three functions but not that those functions do the right thing together. With the shared fake in place it no longer needs to. Replace it with a version that runs the real permission check, the real reminder plan and the real push registration, and fakes only what sits outside the app: expo-notifications (from the setup file), expo-constants, which holds the EAS project ID that push needs, and fetch, which would otherwise post the token to the notify service:
cat > src/notifications/__tests__/ReminderPrompt.test.tsx <<'TSX'
import { render, screen, userEvent, waitFor } from '@testing-library/react-native'
import * as Notifications from 'expo-notifications'
import { ReminderPrompt } from '../ReminderPrompt'
// expo-notifications is the shared fake from jest.setup.ts. Push registration also reads the
// EAS project ID from expo-constants and posts the token with fetch, so those two are replaced here.
jest.mock('expo-constants', () => ({
__esModule: true,
default: { expoConfig: { extra: { eas: { projectId: 'larkfield-test-project' } } } },
}))
const appointment = { id: '42', startsAt: '2030-01-15T10:30:00Z', practitionerName: 'Dr Amina Okafor' }
const realFetch = global.fetch
const fetchMock = jest.fn(async (_url: string, _init: RequestInit) => ({ ok: true, status: 204 }))
beforeEach(() => {
global.fetch = fetchMock as unknown as typeof fetch
})
afterEach(() => {
global.fetch = realFetch
})
test('asks for permission only when the patient chooses reminders, then schedules both', async () => {
jest
.mocked(Notifications.getPermissionsAsync)
.mockResolvedValueOnce({ status: 'undetermined', granted: false, canAskAgain: true } as never)
const user = userEvent.setup()
await render(<ReminderPrompt appointment={appointment} patientId="patient-7" />)
expect(Notifications.getPermissionsAsync).not.toHaveBeenCalled()
await user.press(screen.getByRole('button', { name: 'Remind me' }))
expect(await screen.findByText(/Reminders are on/)).toBeOnTheScreen()
expect(Notifications.requestPermissionsAsync).toHaveBeenCalledTimes(1)
const scheduled = jest.mocked(Notifications.scheduleNotificationAsync).mock.calls.map(([request]) => request.identifier)
expect(scheduled).toEqual(['appointment-42-24h', 'appointment-42-2h'])
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
const [url, init] = fetchMock.mock.calls[0]
expect(url).toMatch(/\/push-tokens$/)
expect(JSON.parse(init.body as string)).toEqual({ patientId: 'patient-7', token: 'ExponentPushToken[test-device]' })
})
test('offers the settings screen after a refusal, and schedules nothing', async () => {
jest
.mocked(Notifications.getPermissionsAsync)
.mockResolvedValueOnce({ status: 'denied', granted: false, canAskAgain: false } as never)
const user = userEvent.setup()
await render(<ReminderPrompt appointment={appointment} patientId="patient-7" />)
await user.press(screen.getByRole('button', { name: 'Remind me' }))
expect(await screen.findByText(/turn them on in your phone's settings/)).toBeOnTheScreen()
expect(screen.getByRole('button', { name: 'Open settings' })).toBeOnTheScreen()
expect(Notifications.requestPermissionsAsync).not.toHaveBeenCalled()
expect(Notifications.scheduleNotificationAsync).not.toHaveBeenCalled()
expect(fetchMock).not.toHaveBeenCalled()
})
test('"Not now" hides the card without a prompt', async () => {
const user = userEvent.setup()
await render(<ReminderPrompt appointment={appointment} patientId="patient-7" />)
await user.press(screen.getByRole('button', { name: 'Not now' }))
expect(screen.queryByText('Want a reminder?')).toBeNull()
expect(Notifications.getPermissionsAsync).not.toHaveBeenCalled()
})
TSXThe three tests make the same promises as part 5's, but each now runs the code behind the card. If askForReminderPermission stopped checking canAskAgain, or planReminders stopped planning the 2-hour reminder, part 5's card test would still pass, because it never called them; this one fails. The appointment is in 2030 so both reminders are always in the future, whatever day the suite runs.
Check it worked
npx jest --ci src/shared src/components src/db src/sync src/notifications src/linkingThe run again reports Test Suites: 13 passed, 13 total and Tests: 63 passed, 63 total, now with all three fakes loaded for each file and part 5's prompt test running the real permission, reminder and push code. Part 1's route test is still left out: with the fake in place it fails with Call setTestDatabase(db) before rendering..., because it renders the root layout without handing the fake a database. The renderRouter step below fixes that.
Step 3 · Test the Appointments tab the way a screen reader reads it
A screen test should find things the way a patient does. Someone using TalkBack or VoiceOver does not see a testID; they hear a role and a name, such as "Cancel GP consultation on Wed 2 Dec, button". React Native Testing Library's getByRole('button', { name }) finds elements by exactly that, so a test written this way fails when the screen stops being usable by a screen reader, not only when the layout changes.
The Appointments tab from part 3 lists upcoming bookings from SQLite and gives each a Cancel button labelled with the service and time. It asks before cancelling, through Alert.alert.
One more thing the test must control is the clock. listUpcoming only shows appointments after "now", so a test that books 2 December 2026 would pass today and fail for ever after that date. jest.useFakeTimers({ now }) fixes the date that new Date() returns; the last steps use the same tool for timers.
Screen tests live outside src/app, because Expo Router treats every file in that folder as a route. Keep them in src/__tests__, next to part 1's route test. Create src/__tests__/appointments-tab.test.tsx:
cat > src/__tests__/appointments-tab.test.tsx <<'TSX'
import { act, render, screen, userEvent } from '@testing-library/react-native'
import { Alert } from 'react-native'
import AppointmentsScreen from '@/app/(tabs)/appointments'
import { addAppointment, listUpcoming } from '@/db/appointments'
import { gpVisit, openTestDatabase } from '@/db/testing/fixtures'
import type { Db } from '@/db/types'
let db: Db
beforeEach(async () => {
jest.useFakeTimers({ now: new Date('2026-12-01T08:00:00.000Z') })
db = await openTestDatabase()
})
afterEach(() => {
jest.useRealTimers()
})
test('lists upcoming appointments soonest first, each with a named cancel button', async () => {
await addAppointment(db, {
...gpVisit,
serviceName: 'Physiotherapy',
practitionerName: 'Dr Amina Bello',
startsAt: '2026-12-09T10:00:00.000Z',
})
await addAppointment(db, gpVisit)
await render(<AppointmentsScreen />)
expect(await screen.findByText('GP consultation with Dr Wanjiru Kamau')).toBeOnTheScreen()
const cancelButtons = screen.getAllByRole('button', { name: /^Cancel / })
expect(cancelButtons).toHaveLength(2)
expect(cancelButtons[0]).toHaveAccessibleName(/^Cancel GP consultation on /)
expect(cancelButtons[1]).toHaveAccessibleName(/^Cancel Physiotherapy on /)
})
test('says what to do when nothing is booked', async () => {
await render(<AppointmentsScreen />)
expect(await screen.findByText(/No upcoming appointments/)).toBeOnTheScreen()
})
test('asks before cancelling, then takes the appointment off the list', async () => {
const alert = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
await addAppointment(db, gpVisit)
const user = userEvent.setup()
await render(<AppointmentsScreen />)
await user.press(await screen.findByRole('button', { name: /^Cancel GP consultation/ }))
expect(alert).toHaveBeenCalledTimes(1)
const [title, , buttons] = alert.mock.calls[0]
expect(title).toBe('Cancel this appointment?')
expect(buttons?.map((b) => b.text)).toEqual(['Keep it', 'Cancel appointment'])
expect(await listUpcoming(db)).toHaveLength(1)
const confirm = buttons?.find((b) => b.style === 'destructive')
await act(async () => {
await confirm?.onPress?.()
})
expect(await screen.findByText(/No upcoming appointments/)).toBeOnTheScreen()
expect(await listUpcoming(db)).toEqual([])
alert.mockRestore()
})
TSX
npx jest src/__tests__/appointments-tab.test.tsxThree details are deliberate:
- The cancel button is matched by the start of its name,
/^Cancel GP consultation/. The time after it is formatted in the phone's language and time zone, so it differs between a laptop in Lagos and a CI machine in the United States. Matching the stable part keeps the test honest about what matters. Alert.alertopens a native dialog, so the test replaces it with a spy and then presses the destructive button itself. That checks the exact question and the two choices the patient sees, and that nothing is cancelled until they confirm.- The list empties without the test reloading anything. The cancel writes to the in-memory database, the fake sends a change event for
appointments, and part 3's hook reloads, exactly as on a phone.
userEvent.press goes through the same press-in and press-out events as a finger, and works with fake timers without extra set-up. user.type does the same for typing: it focuses the field and enters one character at a time, firing the change events a keyboard would. Part 2's src/components/BookingForm.test.tsx fills in all four booking fields with it, and the src/components folder was in both runs in the first two steps, so you have already seen those typing tests pass under this configuration.
Check it worked
Jest reports Tests: 3 passed, 3 total. To see the role query earn its place, delete accessibilityRole="button" from the Cancel Pressable in src/app/(tabs)/appointments.tsx and run the file again: the first and third tests fail because no button is named "Cancel", which is also what a screen reader user would hear. Put the line back.
Step 4 · Bring part 1's route test up to date with renderRouter
Expo Router's testing library renders the real navigation tree from a folder of routes, starts at any URL, and adds matchers such as toHavePathname. Part 1's src/__tests__/routes.test.tsx already uses it, pointed at ./src/app, so it loads your actual layouts: the root stack, the tabs and, since parts 3 to 5, the DatabaseProvider, part 4's OutboxSync and part 5's useReminderTaps. Under this suite those get the fake SQLite, NetInfo's mock (which never reports a connection unless a test tells it to) and the notifications recorder.
That is why the last two steps left it out: the root layout now asks the fake for a database, and part 1's tests never hand it one. Keep the file where the series put it and replace it with a version that opens a test database before each test. It keeps part 1's three checks, with the detail-screen check extended, and adds what parts 3 and 6 promised: the Appointments tab shows what is in SQLite, a link to an appointment has a way back to the tabs, a short SMS link lands in the same place after the rewrite, and an unknown ID shows a message instead of crashing. renderRouter returns a promise and switches on Jest's fake timers itself, keeping the current time, so set the fixed date first. Replace src/__tests__/routes.test.tsx:
cat > src/__tests__/routes.test.tsx <<'TSX'
import { renderRouter, screen, testRouter } from 'expo-router/testing-library'
import { addAppointment } from '@/db/appointments'
import { gpVisit, openTestDatabase } from '@/db/testing/fixtures'
import { rewriteIncomingPath } from '@/linking/rewrite'
beforeEach(async () => {
jest.useFakeTimers({ now: new Date('2026-12-01T08:00:00.000Z') })
// The root layout's DatabaseProvider and OutboxSync read this database through the fake expo-sqlite.
const db = await openTestDatabase()
await addAppointment(db, gpVisit)
})
afterEach(() => {
jest.useRealTimers()
})
// Part 1's three checks
test('the app opens on the Book tab with all three tabs', async () => {
await renderRouter('./src/app', { initialUrl: '/' })
expect(screen).toHavePathname('/book')
expect(await screen.findByText('What do you need?')).toBeOnTheScreen()
expect(screen.getByText('General check-up')).toBeOnTheScreen()
for (const tab of ['Book', 'Appointments', 'Profile']) {
expect(screen.getByRole('button', { name: new RegExp(`^${tab}, tab`) })).toBeOnTheScreen()
}
})
test('the time screen lists only the practitioners for that service', async () => {
await renderRouter('./src/app', { initialUrl: '/book/vaccination' })
expect(await screen.findByText('Nurse Grace Wanjiru')).toBeOnTheScreen()
expect(screen.getByText('Dr Chidi Okafor')).toBeOnTheScreen()
expect(screen.queryByText('Ama Mensah')).toBeNull()
})
test('an appointment link opens the detail screen, with a way back to the tabs', async () => {
await renderRouter('./src/app', { initialUrl: '/appointments/42' })
expect(screen).toHavePathname('/appointments/42')
expect(await screen.findByText('Dr Chidi Okafor')).toBeOnTheScreen()
expect(screen.getByText(/arrive 10 minutes early/)).toBeOnTheScreen()
expect(testRouter.canGoBack()).toBe(true)
})
// What parts 3 and 6 added
test('the Appointments tab lists the booking stored in SQLite', async () => {
await renderRouter('./src/app', { initialUrl: '/appointments' })
expect(screen).toHavePathname('/appointments')
expect(await screen.findByText('GP consultation with Dr Wanjiru Kamau')).toBeOnTheScreen()
})
test('a short SMS link lands on the same screen after the rewrite', async () => {
const path = rewriteIncomingPath('https://larkfield.example/r/42')
await renderRouter('./src/app', { initialUrl: path })
expect(screen).toHavePathname('/appointments/42')
expect(await screen.findByText('Dr Chidi Okafor')).toBeOnTheScreen()
})
test('an unknown appointment shows a message, not a crash', async () => {
await renderRouter('./src/app', { initialUrl: '/appointments/999' })
expect(await screen.findByText('There is no appointment 999.')).toBeOnTheScreen()
})
TSX
npx jest src/__tests__/routes.test.tsxThe detail screen is still part 1's, which reads src/data/appointments.ts, so appointment 42 is Dr Chidi Okafor's check-up; the Appointments tab is part 3's, which reads SQLite, so it shows the fixture's GP consultation. If you have already moved your detail screen to the database, open it with the ID that addAppointment returns and assert the text your screen shows. Write assertions against what the patient reads, not against component names.
renderRouter does not run +native-intent, which only exists on a phone, so the short-link test calls part 6's rewriteIncomingPath itself and hands the result to the router. Between them, part 6's table of URLs and this test cover the whole path from an SMS link to a screen. The back-button check relies on unstable_settings.anchor being (tabs) in the root layout, as part 1 set it, which puts the tabs under a screen opened from a link. Without it, a patient who arrives from an SMS link meets a screen with no way out.
Check it worked
Jest reports Tests: 6 passed, 6 total. Now run every test file, including the screen test from the last step:
npx jest --ciFor the first time in this part every file runs, part 1's included: Test Suites: 15 passed, 15 total and Tests: 72 passed, 72 total. If every route test fails with a message about a route that cannot be found, check that the path is ./src/app relative to the project root, which is where Jest runs. If they fail with Call setTestDatabase(db) before rendering..., the beforeEach that calls openTestDatabase() is missing.
Step 5 · Take control of the clock in the reminder logic
Part 5's reminder tests pass now into planReminders by hand. That works for the pure function, but scheduleReminders is called from the app with no now at all, so those tests never check the default. Jest's fake timers replace Date as well as setTimeout and setInterval: jest.setSystemTime jumps the clock to a moment, and jest.advanceTimersByTime moves it forward, firing any timers that fall due on the way.
This file also shows the shared fake at work. It has no jest.mock line: expo-notifications is already the recorder from the setup file. Create src/notifications/__tests__/reminder-clock.test.ts:
cat > src/notifications/__tests__/reminder-clock.test.ts <<'TS'
import * as Notifications from 'expo-notifications'
import { planReminders, scheduleReminders } from '../reminders'
const HOUR = 60 * 60 * 1000
const appointment = { id: '42', startsAt: '2026-12-03T10:30:00Z', practitionerName: 'Dr Amina Okafor' }
const identifiers = () => planReminders(appointment).map((r) => r.identifier)
beforeEach(() => {
jest.useFakeTimers({ now: new Date('2026-12-01T08:00:00Z') })
})
afterEach(() => {
jest.useRealTimers()
})
test('two days ahead, both reminders are planned', () => {
expect(identifiers()).toEqual(['appointment-42-24h', 'appointment-42-2h'])
})
test('as the clock moves on, reminders that have passed drop out', () => {
jest.setSystemTime(new Date('2026-12-02T12:00:00Z')) // after the 24-hour reminder
expect(identifiers()).toEqual(['appointment-42-2h'])
jest.advanceTimersByTime(20.5 * HOUR) // 08:30 on the day, the 2-hour reminder's own time
expect(identifiers()).toEqual([])
})
test('scheduleReminders reads the same clock when the app passes no time', async () => {
jest.setSystemTime(new Date('2026-12-03T07:00:00Z'))
await scheduleReminders(appointment)
const schedule = jest.mocked(Notifications.scheduleNotificationAsync)
expect(schedule).toHaveBeenCalledTimes(1)
expect(schedule.mock.calls[0][0]).toMatchObject({ identifier: 'appointment-42-2h' })
})
TS
npx jest src/notificationsafterEach puts the real timers back, so a fixed clock never leaks into the next test. The reminder at exactly 08:30 is dropped because part 5 only schedules reminders more than a minute ahead; the test pins that rule down at its edge.
Check it worked
Jest runs part 5's four files and the new one together: Test Suites: 5 passed, 5 total and Tests: 18 passed, 18 total, three of them new. In planReminders, change reminder.date.getTime() > now.getTime() + 60_000 to true and run npx jest src/notifications again: the new file's second and third tests fail, and so does part 5's skips reminders whose time has already passed, because reminders whose time has passed are now planned and scheduled. Put it back.
Step 6 · Drive the sync with NetInfo events and the retry timer
Part 4's OutboxSync component starts a sync when NetInfo reports a connection and, after a failed send, sets a timer to try again. Part 4 tested the sync function against the mock API; this test checks the wiring around it, with the network replaced at its two edges: NetInfo's mock decides what the phone thinks of its connection, and fetch is replaced so the test decides what the clinic answers.
The test captures the listener OutboxSync passes to NetInfo.addEventListener, so it can play "offline" and then "connected". Then it makes the first send fail, and moves the fake clock forward until the retry timer fires. Create src/sync/outbox-sync.test.tsx:
cat > src/sync/outbox-sync.test.tsx <<'TSX'
import NetInfo, { type NetInfoState } from '@react-native-community/netinfo'
import { act, render, waitFor } from '@testing-library/react-native'
import { addAppointment } from '@/db/appointments'
import { gpVisit, openTestDatabase } from '@/db/testing/fixtures'
import type { Db } from '@/db/types'
import { enqueueBooking, getOutboxRow } from './outbox'
import { OutboxSync } from './outbox-sync'
const NOW = new Date('2026-12-01T08:00:00.000Z')
const realFetch = global.fetch
const fetchMock = jest.fn()
let db: Db
let reportNetwork: (state: NetInfoState) => void = () => {}
function connection(isConnected: boolean) {
return { type: isConnected ? 'cellular' : 'none', isConnected, isInternetReachable: isConnected, details: null } as NetInfoState
}
function clinicReply(status: number, body: unknown) {
return { status, text: async () => JSON.stringify(body) }
}
const outboxRow = () => getOutboxRow(db, 'key-1')
beforeEach(async () => {
jest.useFakeTimers({ now: NOW })
db = await openTestDatabase()
const appointmentId = await addAppointment(db, gpVisit)
await enqueueBooking(
db,
{
appointmentId,
serviceId: gpVisit.serviceId,
practitionerId: gpVisit.practitionerId,
startsAt: gpVisit.startsAt,
patientName: gpVisit.patientName,
phone: '+2348031234567',
dateOfBirth: '1990-04-23',
reason: gpVisit.reason,
},
{ idempotencyKey: 'key-1', now: NOW.getTime() },
)
jest.mocked(NetInfo.addEventListener).mockImplementation((listener) => {
reportNetwork = listener
return jest.fn()
})
global.fetch = fetchMock as unknown as typeof fetch
})
afterEach(() => {
global.fetch = realFetch
jest.useRealTimers()
})
test('waits while the phone is offline, then sends once with the idempotency key', async () => {
fetchMock.mockResolvedValue(clinicReply(201, { id: 'bk_1' }))
await render(<OutboxSync />)
await act(async () => reportNetwork(connection(false)))
expect(fetchMock).not.toHaveBeenCalled()
await act(async () => reportNetwork(connection(true)))
await waitFor(async () => expect((await outboxRow())?.status).toBe('confirmed'))
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('http://127.0.0.1:4010/bookings')
expect(init.headers).toMatchObject({ 'Idempotency-Key': 'key-1' })
})
test('tries again on its own timer after a failed send', async () => {
fetchMock
.mockRejectedValueOnce(new TypeError('Network request failed'))
.mockResolvedValue(clinicReply(201, { id: 'bk_1' }))
await render(<OutboxSync />)
await act(async () => reportNetwork(connection(true)))
await waitFor(async () => expect((await outboxRow())?.attempts).toBe(1))
expect((await outboxRow())?.status).toBe('pending')
await act(() => jest.advanceTimersByTimeAsync(2_000))
await waitFor(async () => expect((await outboxRow())?.status).toBe('confirmed'))
expect(fetchMock).toHaveBeenCalledTimes(2)
})
TSX
npx jest src/sync/outbox-sync.test.tsxThe first retry waits between 1 and 2 seconds (part 4's backoff with jitter), so moving the clock 2 seconds always reaches it, and the test takes milliseconds instead of seconds. advanceTimersByTimeAsync also lets the promises started by each timer settle, which the plain advanceTimersByTime does not.
The failed send matters on Larkfield's patients' phones. A prepaid bundle that runs out mid-request looks exactly like this test: NetInfo still says connected, the request fails, and the booking must wait for the timer rather than be lost.
Check it worked
Jest reports Tests: 2 passed, 2 total. In src/sync/outbox-sync.tsx, change if (!stopped && result.nextAttemptAt !== null) to if (false) and run the file again: the second test fails after one send, because nothing schedules the retry. Put it back.
Step 7 · Collect coverage for the data and sync code
Coverage shows which lines and branches the tests ran. It cannot tell you whether the tests check the right things, but a branch that never runs is certainly not checked. Measure the two folders where a mistake loses a patient's booking, src/db and src/sync, leave out the test helpers, and set a floor so coverage cannot quietly fall.
Replace jest.config.js with the full version:
cat > jest.config.js <<'JS'
/** @type {import('jest').Config} */
module.exports = {
preset: 'jest-expo',
// Runs before each test file, after Jest itself is ready.
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
// Build output from `npx expo export` is never a test.
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/.expo/'],
// Forget recorded calls between tests, so one test cannot pass because of another.
clearMocks: true,
// The first render in a file loads React Native and can be slow, more so with coverage on.
testTimeout: 15_000,
// Coverage: the code that stores and sends bookings, without the test helpers.
collectCoverageFrom: [
'src/db/**/*.{ts,tsx}',
'src/sync/**/*.{ts,tsx}',
'!**/testing/**',
'!**/*.test.{ts,tsx}',
'!**/__tests__/**',
],
coverageReporters: ['text', 'text-summary', 'lcov'],
// The run fails if either folder drops below these percentages.
coverageThreshold: {
'./src/db/': { statements: 90, branches: 50, functions: 85, lines: 90 },
'./src/sync/': { statements: 90, branches: 80, functions: 80, lines: 90 },
},
}
JS
grep -qx 'coverage/' .gitignore || echo 'coverage/' >> .gitignoreThe floors sit a few points under what the suite reaches today, so they catch a real drop without failing on noise. Raise them as you add tests; never lower one to make a pull request pass without reading what stopped being covered. The report is written to coverage/, which is build output, so it goes in .gitignore. Run the whole suite with coverage, with the mock API still running in the second terminal:
npm run test:coverage -- --ciCheck it worked
Every suite passes: in the project as this series builds it, Test Suites: 17 passed, 17 total and Tests: 77 passed, 77 total (the 14 files from parts 1 to 6, two of them rewritten in this part, plus the appointments screen test, the reminder clock test and the outbox sync test), or more if you kept extra tests of your own. Below the results, Jest prints a table with one row per file in src/db and src/sync: the percentage of statements, branches, functions and lines run, and the line numbers that never ran. Expect something like 95% of lines in each folder, with branches lower in src/db, and no coverage threshold error at the end. (types.ts shows zeros because it holds only types, which leave no code to run.) Open coverage/lcov-report/index.html in a browser to see each file with the lines that never ran highlighted.
Read the uncovered lines rather than chasing the number. In src/db/database-provider.tsx the uncovered part is the loading screen, which only appears while the real native database opens; that is a fair gap. In src/sync/transport.ts the uncovered line is the catch for a reply that is not JSON, such as an HTML error page from a mobile network's proxy or a captive portal. Phones on prepaid data meet that often, so it deserves a test: a good first addition to src/sync/outbox-sync.test.tsx, with fetch answering text: async () => '<html>'.
Step 8 · Run the suite on every pull request
Tests that only run on your laptop stop being run. A GitHub Actions workflow runs the same suite on every pull request and shows a red cross on the pull request when anything fails, including the coverage floors.
The job does what you have done by hand: install exactly what package-lock.json lists, start the mock clinic API in the background, wait until it answers, and run Jest with --ci, which fails instead of writing new snapshots. The coverage report is uploaded so a reviewer can open it from the run's page. Create .github/workflows/test.yml:
mkdir -p .github/workflows
cat > .github/workflows/test.yml <<'YAML'
name: Tests
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: tests-${{ github.ref }}
cancel-in-progress: true
jobs:
jest:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 26
cache: npm
- name: Install dependencies
run: npm ci
- name: Start the mock clinic API
run: |
node mock-api/server.mjs > mock-api.log 2>&1 &
for i in $(seq 1 30); do
curl -fs http://127.0.0.1:4010/health > /dev/null && exit 0
sleep 1
done
echo "The mock clinic API did not start"
cat mock-api.log
exit 1
- name: Run Jest with coverage
run: npx jest --ci --coverage
- name: Keep the coverage report
if: always()
uses: actions/upload-artifact@v7
with:
name: coverage
path: coverage/
retention-days: 14
YAMLpermissions: contents: read gives the job only what it needs to check out the code, and concurrency cancels a run that a newer push to the same branch has made pointless. The workflow names actions by major version tag. For a team, pin each one to a full commit SHA instead, as described in harden GitHub Actions workflows.
Commit the workflow with the rest of the project and push a branch:
git add .github/workflows/test.yml jest.config.js jest.setup.ts src .gitignore package.json
git commit -m "Run the Jest suite on every pull request"
git push -u origin add-test-suiteOpen a pull request for the branch on GitHub. To make the check required, go to the repository's Settings, then Rules, add a branch ruleset for main, and add jest under the required status checks.
Check it worked
Before you push, check the file is valid YAML and has the trigger and the test command you expect:
npx --yes yaml@2.9.1 valid < .github/workflows/test.yml && echo "valid YAML"
npx --yes yaml@2.9.1 --json < .github/workflows/test.yml \
| node -e "const [w] = JSON.parse(require('fs').readFileSync(0, 'utf8')); console.log(Object.keys(w.on).join(' '), '|', w.jobs.jest.steps.map((s) => s.run ?? s.uses).filter((r) => /jest|actions/.test(r)).join(' | '))"The first command prints valid YAML. The second prints the two triggers, pull_request push, then the three actions and npx jest --ci --coverage. On GitHub, the pull request shows a "Tests / jest" check that turns green when the run finishes, and the run's summary page lists a coverage artifact.
Stop the mock API with Ctrl+C in the second terminal. Keep ~/larkfield-app-demo: the last part of the series uses this suite before release.
Next steps
- Finish the series with an accessibility pass, version numbers and a Maestro smoke test: get the Larkfield app ready for release.
- Compare the same ideas on the web, with Vitest: test React components with Vitest and Testing Library.
Part of these paths
Related tutorials
- Get the Larkfield app ready for release: accessibility, versions and a Maestro smoke testYou will take the Larkfield Clinic Expo app through a release checklist, with tested accessible slot buttons, a version policy EAS enforces, the icon, splash and permissions checked by one script, and a Maestro flow that books an appointment, then hand it to EAS and clean up the series.
- Build the Larkfield booking form with React Hook Form and ZodYou will have a tested booking details screen in the Larkfield Clinic Expo app that validates name, mobile number, date of birth and reason with one shared Zod schema, moves focus field to field, announces errors to screen readers and cannot be submitted twice.
- Write end-to-end mobile tests with MaestroYou will have a small Maestro suite for a mobile app, with stable test IDs in React Native or Flutter, a shared sign-in flow fed by environment variables, smoke and full runs split by tags, and a CI job that runs the smoke flows on an Android emulator.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials