Mock the Network, Not Your Code
Intercept HTTP with Mock Service Worker so the real fetch client stays under test, share handlers across a suite, and force one-off outcomes such as a 500 for a single test.
Contentsand lesson path
On this page
- The problem
- Why mock at the network boundary
- Step 1: describe the responses
- Step 2: wire interception into Vitest
- Step 3: force one-off outcomes
- What not to do with mocks
- Check your understanding
- Apply it
- Review prompt
Lessons of Component & End-to-End Testing
- What to Test in a Frontend, and at Which Level Concept · 20 min
- Component Tests That Read Like User Stories Worked example · 25 min
- Mock the Network, Not Your Code Worked example · 20 min
- End-to-End Journeys with Playwright Worked example · 25 min
- Lab: Test a Checkout Flow at Every Level Lab · 30 min
- Check: Fix the Flaky and the Brittle Knowledge check · 8 questions
What you will learn
- Isolate tests from real services by mocking HTTP at the network level (for example with Mock Service Worker) and cover loading, error and success states.
Prerequisites: React Components & State
01. The problem
The search component from the previous lesson calls searchProducts, which calls fetch (the fetch API itself is covered in the async JavaScript skill). To test all four visible states without a backend, there are two broad options: replace the searchProducts module with a fake, or intercept the HTTP request itself and answer it. This lesson argues for the second, and shows how Mock Service Worker (MSW) does it.
02. Why mock at the network boundary
Module mocking (vi.mock('./api')) replaces your code with a stub. Whatever the stub returns is what the test sees, so everything the real module does escapes the test: the URL it builds, the query parameter it encodes, the status code it treats as a failure, the shape it parses. You end up testing the component against a fictional client, and the client itself against nothing.
Interception at the network boundary keeps your real code in the loop. searchProducts really runs, fetch really produces a request, MSW answers it with a canned response, and the component renders from the parsed reply. Only the wire is faked. The same handler file later serves the browser during development and Storybook, so one definition of what the API returns powers tests and local interface work alike.
Module mocking still has its place: it suits the SDK you cannot run in tests (a maps library, a payment widget), time or randomness you need to pin, and boundaries that have nothing to do with HTTP. The distinction to draw is whose code is under test. If the mocked unit is yours — a client, a wrapper, a hook that shapes the request — mocking it removes exactly the behaviour you meant to verify. If it is someone else’s dependency, stubbing it keeps the test about your code.
03. Step 1: describe the responses
Handlers describe the requests MSW intercepts and the responses it returns. They read like a miniature API: a method, a URL pattern, and a function that answers. This one filters a small catalogue by the q query parameter, which gives the tests meaningful data instead of magic values:
import { http, HttpResponse } from 'msw/http';
import type { Product } from '../api';
const catalogue: Product[] = [
{ id: 1, name: 'Trail shoes', price: 89.5 },
{ id: 2, name: 'Running shoes', price: 74 },
];
export const handlers = [
http.get('*/api/products', ({ request }) => {
const query = new URL(request.url).searchParams.get('q') ?? '';
return HttpResponse.json(
catalogue.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase()),
),
);
}),
];Three details carry weight. The pattern '*/api/products' matches the path on any host, so tests need no base URL. request.url is the real URL your client produced — if searchProducts forgot to encode the query, these handlers would see it. And HttpResponse.json sets both the body and the Content-Type, exactly as a real server would.
Handlers are plain data, which makes them easy to keep faithful. Model the outcomes your real API can produce: populated lists, empty lists, malformed payloads, a slow response (MSW's delay helper, imported from msw/utils/delay in version 3) and each error status your client distinguishes. A suite whose handlers cover the API contract doubles as executable documentation of that contract — a new teammate can read one file to learn what the products endpoint returns in every situation.
04. Step 2: wire interception into Vitest
Install MSW first. This lesson and the lab pin MSW 3.0.8. Version 3 (first released on 28 September 2026) needs Node 22 or later and changed two things this code relies on, so code written for MSW 2 needs both edits: http and HttpResponse are imported from msw/http rather than the package root, and the onUnhandledRequest option of server.listen() is now called onUnhandledFrame. The old option name is not reported as an error: MSW 3 ignores it and falls back to its default, 'warn', which quietly removes the safety net described next.
In a browser, MSW interception is a real service worker; under Vitest, setupServer from msw/node intercepts requests inside the Node process. Three lifecycle calls give every test the same clean network: listen before all tests, resetHandlers after each one, close after the last. With onUnhandledFrame: 'error', a request that no handler matches prints an MSW error and its fetch rejects, instead of the default warning followed by the real network — so you hear at once when a component calls an endpoint nobody defined:
npm install -D [email protected]import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterAll, afterEach, beforeAll } from 'vitest';
import { server } from './mocks/server';
// MSW 3 name; MSW 2 called this option onUnhandledRequest
beforeAll(() => server.listen({ onUnhandledFrame: 'error' }));
afterEach(() => {
cleanup();
server.resetHandlers();
});
afterAll(() => server.close());05. Step 3: force one-off outcomes
Shared handlers answer most tests. When one test needs a different outcome — a server failure, a delay, a different payload — server.use() adds a runtime handler that takes precedence for that test, and resetHandlers() in afterEach removes it again afterwards. Tests stay independent: none of them edits the shared file, and none of them sees another override.
import { http, HttpResponse } from 'msw/http';
import { server } from './mocks/server';
it('shows an error message when the request fails', async () => {
server.use(
http.get('*/api/products',
() => new HttpResponse(null, { status: 500 })),
);
render(<ProductSearch />);
expect(await screen.findByRole('alert')).toHaveTextContent(/went wrong/i);
expect(screen.queryByRole('list')).not.toBeInTheDocument();
});The request fails with status 500, searchProducts throws, the component renders role="alert", and the list is gone. Nothing about the component had to change to make this test possible — that is the point. Loading, success and empty states follow the same pattern with the shared handler and were covered in the previous lesson:
The same mechanism scales to the rarer outcomes. A test that needs a slow network adds a handler that awaits delay(1000) before answering, then asserts the loading note is still on screen. A test that needs a malformed payload returns a body with the wrong shape, and the test documents what the component shows when the contract breaks. Each is a few lines on top of the shared file, and each is removed again by resetHandlers() before the next test runs.
RUN v5.1.2
✓ src/product-search.test.tsx (3 tests)
Test Files 1 passed (1)
Tests 3 passed (3)06. What not to do with mocks
07. Check your understanding
08. Apply it
Extend the suite you built in the previous lesson. Add a runtime handler that delays the response by a second and confirm the loading note is what a user sees during that second. Then add a handler for a second endpoint your component family uses, and make one test force it to return a malformed payload — what should the component show then? Write that state down before you decide, because it is a product decision, not a testing one.
09. Review prompt
Without looking back: explain why mocking at the network boundary keeps more of your code under test than module mocking. Name the three lifecycle calls and what each does. Then describe how one test forces a 500 while the rest of the suite keeps the shared handlers.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.