Mocking a UK Address Lookup API in Your Tests

Testing · November 2026 · 10 min read

Stop paying for postcode lookups in CI. Working MSW and Python examples for mocking an address lookup service, covering timeouts, rate limits and empty results, with safe fixtures.

Almost every UK checkout and signup form calls an address lookup API: type a postcode, pick your address from a list. That call is also one of the most common reasons a test suite is slow, flaky or quietly spending money. This guide shows how to mock it properly, with working code, and how to keep the mock honest.

Why the real API does not belong in your tests

A postcode lookup service is a paid, rate-limited, external dependency. Calling it from automated tests causes predictable problems:

  • Cost. Most providers charge per lookup. A suite that runs on every commit, in parallel, across branches, can use thousands of lookups a day.
  • Flakiness. The network is slow and occasionally fails, so tests fail for reasons unrelated to your code.
  • Rate limits. Parallel CI jobs hit them, and your tests fail in bursts.
  • Uncontrollable cases. You cannot ask the real API to time out, return an empty list or send a malformed response, and those are exactly the paths that need testing.
  • Real addresses in fixtures. Snapshots and logs of real lookup results fill your repository with real people's addresses.

The answer is to mock at the HTTP boundary for almost every test, and keep one small, separate check against the real service.

The shape of a lookup

Most UK postcode lookup APIs follow the same pattern. Exact field names vary by provider, so match your mock to the one you use:


GET /lookup?postcode=SW1A1AA

200 OK
{
  "postcode": "SW1A 1AA",
  "addresses": [
    { "line1": "Flat 1", "line2": "10 Example Street", "town": "LONDON", "postcode": "SW1A 1AA" },
    { "line1": "Flat 2", "line2": "10 Example Street", "town": "LONDON", "postcode": "SW1A 1AA" }
  ]
}

Your code then needs to handle at least these outcomes:

Mocking in the browser and in Node with MSW

Mock Service Worker intercepts requests at the network level, so your application code calls fetch exactly as it does in production. The same handlers work in unit tests (Node) and in the browser.


// mocks/addressLookup.js
import { http, HttpResponse, delay } from 'msw';

const LOOKUP = 'https://example.com/postcode-lookup';

// Fictional addresses on a real postcode district. Never real delivery points.
const FIXTURES = {
  'SW1A1AA': [
    { line1: 'Flat 1', line2: '10 Example Street', town: 'LONDON', postcode: 'SW1A 1AA' },
    { line1: 'Flat 2', line2: '10 Example Street', town: 'LONDON', postcode: 'SW1A 1AA' }
  ]
};

export const handlers = [
  http.get(LOOKUP, async ({ request }) => {
    const postcode = new URL(request.url).searchParams.get('postcode')?.replace(/\s+/g, '').toUpperCase();

    if (postcode === 'ZZ99SLOW') {
      await delay('infinite');               // exercise your timeout
    }
    if (postcode === 'ZZ99RATE') {
      return new HttpResponse(null, { status: 429 });
    }
    if (postcode === 'ZZ99DOWN') {
      return new HttpResponse(null, { status: 503 });
    }
    const addresses = FIXTURES[postcode];
    return addresses
      ? HttpResponse.json({ postcode, addresses })
      : HttpResponse.json({ postcode, addresses: [] });
  })
];

Wire it into the test runner once:


// test/setup.js
import { setupServer } from 'msw/node';
import { handlers } from '../mocks/addressLookup';

export const server = setupServer(...handlers);

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

onUnhandledRequest: 'error' is the important line. Any request that escapes the mock fails the test loudly, so a real lookup can never slip back into CI unnoticed.

Each failure case is now a one-line test:


test('falls back to manual entry when the lookup service is down', async () => {
  render(<AddressForm />);
  await user.type(screen.getByLabelText(/postcode/i), 'ZZ99 DOWN');
  await user.click(screen.getByRole('button', { name: /find address/i }));
  expect(await screen.findByLabelText(/address line 1/i)).toBeVisible();
});

The magic postcodes use the ZZ99 prefix deliberately. ZZ is not a postcode area, so these values can never collide with a real lookup, and anyone reading the test can see at once that they are artificial.

Mocking in Python with responses

The same approach for a Python back end that calls the lookup service with requests:


import re
import responses

LOOKUP = re.compile(r"https://example\.com/postcode-lookup.*")

@responses.activate
def test_lookup_timeout_falls_back_to_manual_entry(client):
    responses.add(responses.GET, LOOKUP, status=503)
    reply = client.get("/checkout/address?postcode=SW1A1AA")
    assert reply.json()["mode"] == "manual"

@responses.activate
def test_lookup_returns_addresses(client):
    responses.add(responses.GET, LOOKUP, json={
        "postcode": "SW1A 1AA",
        "addresses": [{"line1": "Flat 1", "line2": "10 Example Street",
                       "town": "LONDON", "postcode": "SW1A 1AA"}],
    })
    reply = client.get("/checkout/address?postcode=SW1A1AA")
    assert len(reply.json()["addresses"]) == 1

responses raises an error for any unregistered URL while a test is decorated with @responses.activate, which gives you the same guarantee as MSW's onUnhandledRequest: 'error'.

Where the fixture data comes from

Fixtures are the weak point of most mocks. Two rules:

  • Do not paste real lookup results into fixtures. A real lookup returns real people's addresses, and fixtures live in version control forever.
  • Do make fixtures structurally valid. If your fixture postcodes break the real format rules, your own validation either rejects them or, worse, gets loosened to accept them. That exact failure is measured in why Faker's UK postcodes fail validation.

Generated addresses fit both rules. The UK address generator produces addresses on real postcode districts and post towns, formatted to Royal Mail conventions, that are never live delivery points. For seed scripts and CI, the REST API returns the same data as JSON, so fixtures can be regenerated rather than hand-maintained. To include the awkward cases (flats, house names, addresses with no street number), see Royal Mail address formatting rules.

Keeping the mock honest

A mock is a claim about how the real service behaves, and it goes stale when the provider changes. Two cheap safeguards:

1. Contract check. Keep one test, outside the main suite, that calls the provider's sandbox or test endpoint and checks that the response still has the fields your mock returns. Run it nightly rather than on every commit, so it costs a few lookups a day. 2. One source of fixtures. Build every mock response from a single fixture module, so a change in the provider's format is fixed in one place.

The same pattern elsewhere

Everything here applies to every external lookup in a UK form: bank account validation, VAT number checks, identity verification. For those, see testing KYC and identity verification flows and the test-data guides for VAT numbers and bank details. The rule is always the same: mock at the boundary, generate the fixtures, and check the contract on a schedule.

More guides