Network Mocking at the Boundary
Intercept HTTP at the network layer so your real client code still runs.
- api
- mocking
- determinism
Problem
Tests that hit a live API are slow, flaky, and fail for reasons unrelated to your code. But mocking your own fetch wrapper means the code you most want to test never runs.
Solution
Intercept at the network boundary instead of stubbing your client. A tool like MSW (Mock Service Worker) answers requests at the transport layer, so your real fetch/axios code, serialization, and error handling all execute against deterministic responses.
Define handlers once and share them between unit, integration, and E2E layers to keep behaviour consistent.
Snippet
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
http.get('/api/users/:id', ({ params }) =>
HttpResponse.json({ id: params.id, name: 'Ada Lovelace' }),
),
);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());Pitfalls
- Mocking your own API client instead of the network — then the test proves nothing about real requests.
- Letting unhandled requests pass silently; set onUnhandledRequest: 'error' to catch drift.
- Forgetting to reset handlers between tests, leaking state across cases.