Quickstart

Quickstart: Mock the public API in unit tests

For fast unit tests, mock the API with a recorded fixture instead of a live call — reserve the sandbox for integration tests. This recipe shows the exact code, uses only the unauthenticated public ring, and links out to the endpoints and the application flow so the reader always has a next step.

2 min read

offlineNo network in unit tests
fixtureRecord once, replay
fastMilliseconds, not seconds

Record a fixture

Capture one real sandbox response and save it. Your test then serves that fixture instead of calling out:

import { vi } from 'vitest';
import productsFixture from './fixtures/products.json';

vi.stubGlobal('fetch', vi.fn(async () => new Response(
  JSON.stringify(productsFixture), { status: 200 },
)));

Keep fixtures fresh

Refresh fixtures from the sandbox on a schedule so they don't drift from the real contract. A weekly job that re-records and diffs is enough to catch breaking changes early.

Frequently asked questions

Mock or hit the sandbox?

Mock in unit tests for speed and isolation; hit the sandbox in a smaller set of integration tests to catch contract drift. Use both.

How do I stop fixtures going stale?

Automate re-recording from the sandbox and fail the job if the shape changed. That way your mocks track the real API.

Funding for UK limited companies

Credicorp lends to your company, not to you personally — short-term working capital with no personal guarantee. See what your business could access.