What you'll learn: By the end of this lesson you will be able to say what an integration test of a front end covers and what it leaves out, choose where to cut the system (a module,
fetch, or the network), write handlers for the happy path and override them per test, turn requests nobody planned for into failures, test loading, error, empty and failed-refresh states without a server, and name the ways a mock can lie to you.
Think of a flight simulator. The pilot uses the real controls, the real checklists and the real instruments; only the sky is fake. Because the sky is under control, you can ask for a storm at minute three, every time. An integration test of a front end is the same: your real screen logic, your real data layer and your real error handling run together, and only the network is replaced by something you control.
The running example is the order history page of a grocery marketplace, the front end of the ShopStream marketplace used in this course: a list of orders, a status filter, a Refresh button and a cancel action. The states of that page are the subject of Error, Loading and Empty States. Here the question is how to test them without a real server.
The core idea
- An integration test runs several real parts together. Here: the screen logic, the data layer that calls
fetch, and the parsing of the response. It checks that they agree with each other, which a test of one part cannot do. - Replace as little as possible, and at the edge. The less of your own code the mock replaces, the more of your code the test exercises. The outermost edge you do not control is the network.
- A mock is a claim about the server. Every handler says "the server answers like this". It is only as good as that claim, so keep it small, strict, and checked against the real contract.
Where to cut
There are three places to put the seam between "real" and "fake". The further out you cut, the more real code runs, and the more setup the test needs.
| Cut at | What you replace | What still runs for real | Typical weakness |
|---|---|---|---|
| The module | The whole data-layer module (a module mock) | The screen only | The test never checks the URL, headers, status handling or parsing |
fetch |
A hand-written function with canned results | Data layer and screen | Each test re-invents the server; easy to forget a check such as ok |
| The network | Handlers that match a method and path and return a response | Data layer, parsing and screen | A little more setup; the handlers must stay true to the server |
MSW (Mock Service Worker) is a widely used library that cuts at the network. Its documentation says it intercepts requests in the browser with the Service Worker API without patching fetch, and in Node by extending classes instead of patching modules, so the test environment stays close to production. Vitest's documentation recommends it for mocking requests and says it uses the @mswjs/interceptors library in Node, so application code does not change.
Figure 1. Where the test cuts the system
How to read this: the two accent boxes are your real code, and they run exactly as in production. The grey box is the only fake. The test pushes on the screen logic and reads the state it produces; it never reaches into the data layer.
Handlers: the mock server
A handler is a small rule: for this method and this path, return this response. In the lab for this lesson (below) it looks like this.
http("GET", "/api/orders", ({ url }) => {
const status = url.searchParams.get("status");
return jsonResponse(status === null ? orders : orders.filter((o) => o.status === status));
}),
http("POST", "/api/orders/:id/cancel", ({ params, headers }) => {
if (!headers.get("idempotency-key")) {
return jsonResponse({ error: "Idempotency-Key header is required" }, 400);
}
// ... find the order, answer 404 or 409 or the cancelled order
}),
The path pattern :id captures a parameter, so one handler serves every order. The second handler enforces a rule the real server is assumed to have: a cancel without an Idempotency-Key header is refused. A mock that accepts anything hides the bug where the client forgot the header; a mock that refuses what the server would refuse finds it.
MSW's Node setup follows the same shape: a server is created from a list of handlers (setupServer(...handlers)), and its page lists three steps for any test runner: enable mocking before all tests (server.listen()), reset handlers between tests (server.resetHandlers()) and restore native modules after all tests (server.close()).
Overrides: one test, one situation
The base handlers describe the sunny day. Most interesting tests need a different day: a 503, a dropped connection, an empty list. Instead of editing the base handlers, a test adds an override that wins for that test and is removed afterwards.
network.use(http("GET", "/api/orders", () => jsonResponse({}, 503)));
await history.refresh();
Two properties keep this safe. Overrides are reset between tests, so a failure scenario in one test cannot leak into the next (Vitest's guide gives the reason in a comment: reset handlers after each test for test isolation). And a one-shot override ({ once: true }) answers a single request and then steps aside, which is how you write "fail the first load, succeed on Try again".
Figure 2. Which handler answers
(logged first)"] --> H{"A handler matches
method and path?
(use() first, then base)"} H -->|"yes"| K{"Result is a
network failure?"} K -->|"no"| RES["Return the Response
(consume once-handlers)"] K -->|"yes"| TE["fetch rejects
with TypeError"] H -->|"no"| U["Record as unhandled,
fetch rejects with
UnhandledRequestError"]
How to read this: the order of the search is the whole rule: the newest override first, the base handlers last, so a test can change one answer without redefining the server. The bottom branch is the safety net described next.
Unhandled requests must be loud
If the code makes a request nobody wrote a handler for, a quiet mock is dangerous: the test may pass while the screen is calling something you never considered. MSW's documentation for onUnhandledRequest (the version 1 page, at the time of reading) lists three behaviours: "bypass" performs the request as-is, "warn" prints a warning, and "error" prints an error, with "warn" as the default. Vitest's guide sets onUnhandledRequest: 'error' in its example and says it ensures an error is thrown whenever a request has no handler.
A subtlety applies to any mock that rejects: the rejection goes through your own error handling. In the lab, a request with no handler makes fetch reject, the data layer turns it into a "network error", and the screen shows an ordinary blocking error. So the lab's mock also records the request, and the shared afterEach asserts the list is empty. The record is the signal; the rejection is only a side effect.
Illustration 1: the minimal example
A request with no handler, and what the screen and the record each say about it. The lab's demo ran it with no handlers at all:
Expected output, captured from a real run (scenarios 6 and 7 of node src/demo.ts, Node 26.13.1):
6. a request no handler matches (the mock rejects it and records it)
views: loading -> error (blocking)
requests: GET /api/orders
unhandled: GET /api/orders
error shown to the user: Network error
7. cancel rules enforced by the mock
o-1001 -> cancelled
o-1002 -> HTTP 409
o-4040 -> HTTP 404
The screen went loading then error (blocking) with "Network error": it looks like an outage. Only the unhandled line shows the truth. Scenario 7 shows the mock applying the server's rules: a shipped order answers 409 and an unknown id 404.
What an integration test asserts
Assert what the user would notice and what the server would see, not the internals.
- The states the user sees. The lab reduces the screen to a pure function,
viewOf(state), that returns names such asloadingorcontent + refresh failed. A test drives the controller and records the sequence of views. - What was sent. The mock logs every request with its method, path, headers and parsed JSON body, so a test can assert that the filter reached the query string and that
Idempotency-Keywas sent. - What the screen does when the answer is bad. A 503, a dropped connection, a body that is not JSON or has the wrong shape: cases a real server rarely gives you on demand.
For tests that render a DOM, the same mock sits underneath. Testing Library's documentation says findBy methods are a combination of getBy queries and waitFor, and that waitFor retries a callback until it stops throwing or a timeout passes (1000 ms by default, every 50 ms). That is a wait on an observable condition, not a fixed sleep; the end-to-end lesson explains why that matters.
Illustration 2: the realistic example, a failed refresh
The order history page has loaded; the shopper presses Refresh; the orders API returns 503. The screen must keep the three orders it has and show a banner. In the lab the test is a few lines, and the demo prints the whole path:
Expected output, captured from a real run (scenarios 2 and 3 of node src/demo.ts, Node 26.13.1):
2. a refresh fails with 503 and the list stays
views: loading -> content -> content + refreshing -> content + refresh failed
requests: GET /api/orders, GET /api/orders
unhandled: none
kept 3 orders, banner: HTTP 503
3. the first load hits a dropped connection, then Try again works
views: loading -> error (blocking) -> loading -> content
requests: GET /api/orders, GET /api/orders
unhandled: none
error after the first load: Network error
In scenario 2 the three orders survive the failed refresh. In scenario 3 a one-shot dropped connection gives a blocking error, and Try again (a second load) succeeds. Both rely on the data layer turning a rejected fetch and a resolved 503 into one error type, and on the screen logic keeping data it has. A unit test of one piece cannot check that; here each is one short test.
Figure 3. A failed refresh through the mock
How to read this: the 503 resolves rather than rejects, because fetch only rejects when the request itself fails; MDN states that a fetch() promise does not reject on HTTP error statuses such as 404 or 504 and that the code must check Response.ok or Response.status. The ok check lives in the data layer, which is why the test runs the data layer for real.
Illustration 3: the failure, newer request wins
A filter change can start a second request while the first still runs; the older answer must not overwrite the newer. The lab's controller numbers each request and ignores a stale answer. The test holds the first request with a gate() (a promise opened by hand), lets the second finish, releases the first and asserts the state still belongs to the second. A fixed delay would make this slow and timing-dependent; a gate makes the order exact.
Build it
The lab is examples/frontend/labs/network-mocking: a small model of request-level mocking in plain TypeScript (not MSW itself: no service worker, nothing patched; the code under test is handed network.fetch). It holds the mock network (src/mockNetwork.ts), the happy-path handlers (src/handlers.ts), the data layer (src/ordersApi.ts), the screen logic (src/orderHistory.ts) and 22 tests that run all of it together.
cd examples/frontend/labs/network-mocking
../../node_modules/.bin/vitest run
node src/demo.ts
The 22 tests passed (Vitest 5.1.0, Node 26.13.1). The demo output above is a verbatim excerpt of examples/frontend/golden/network-mocking.txt. The README has a "break it" experiment: deleting the response.ok check makes four tests fail, which a module mock would never catch. Nothing here was observed in a browser.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Mock at the network | Data layer, parsing and error handling really run | Handlers to write and keep true |
| Mock the module | Fast, tiny tests | Never checks URL, headers or ok |
| Strict unhandled requests | Surprise calls fail the test | Every new call needs a handler |
| Overrides per test | Failure cases on demand | A reset step that must not be forgotten |
| A gate instead of a delay | Exact, fast ordering | A little more test code |
In practice: a checkout bug that no test could see
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The cancel button on the order history page "does nothing" for some shoppers. The API team required an idempotency key on every write, and the cancel call in one code path was left out of the change. The team's tests all pass.
Starting architecture
Figure 4. Tests that replace the data layer
How to read this: in tests the screen talks to a fake data layer; the real one, where the header is set, is only used in production. The warning box is where the gap is.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| One test for the missing header | This bug | One test | The next contract change is missed |
Mock fetch per test |
Data layer runs | Each test invents a server | Inconsistent mocks |
| Shared strict network handlers | Data layer runs against one mock | Handlers to maintain | Drift from the real server |
The decision
| Field | Decision record |
|---|---|
| Context | The data layer is never run in screen tests, so a missing header cannot fail any test. |
| Decision | Replace the network, not the data layer. One shared set of handlers that enforce the documented rules (the header, 404 and 409 answers), per-test overrides, strict unhandled requests. |
| Consequences, good | Header, status and parsing mistakes fail tests; failure states are cheap to test. |
| Consequences, bad | The handlers are a second copy of the server's rules. |
| Revisit when | A contract test (a separate lesson) checks the handlers against the real API automatically. |
Rollout and verification
- Write the base handlers for the calls the screen makes, with the server's refusals.
- Move the screen tests one by one from the fake to the network mock.
- Add the shared check: after every test, nothing unhandled and handlers reset.
- Add the missing-header test: it must fail on the old code and pass on the fix.
The 2 a.m. failure
The mock says an endpoint returns a field the real API renamed a week ago. All tests pass; production shows blank prices.
First three checks: (1) compare one real response with the handler's body; (2) look for the last API change in the server's changelog; (3) check whether the data layer's shape check is the one that rejects it in production. Mitigation: update the handler and the parser together. Follow-up: run contract checks against the real API on a schedule so the mock cannot drift silently.
Architect's notes
- Cut at the network when you can. It is the highest seam that still lets a test run without a server.
- Make the mock as strict as the server. A forgiving mock hides the bugs integration tests exist to find.
- Fail on the unexpected. An unhandled request is a missing decision, not noise.
- Keep handlers small and shared. One source of mock behaviour for every test.
Common mistakes
- Mocking the data layer in every test, so the real
fetchcode never runs. - A permissive mock that returns success for a request the real server would refuse.
- Handlers that leak between tests, because overrides were not reset.
- Reading a mock rejection as proof when the screen's own error handling swallowed it.
- Fixed-delay mocks that make tests slow and order-dependent.
- Treating the mock as the contract. It is a copy of one; the contract lives with the API.
Key takeaways
- An integration test runs your own parts together and fakes only the outside world.
- The network is the highest useful seam; a module mock skips the code most likely to be wrong.
- Handlers should enforce the rules the server enforces, including its refusals.
- Add overrides per test and reset them after; use one-shot handlers for "fail once, then work".
- Make unhandled requests fail and record them, because your own error handling can hide the rejection.
- A mock can drift from the server; a contract test is what keeps them honest.
Practice exercises
Exercise 1: Starter (30 min). Run the lab's tests, then add a handler for GET /api/orders/:id and a test that an unknown id gives an http error with status 404.
Exercise 2: Intermediate (2 hours). Add a { once: true } override that fails the cancel call with 503 on the first attempt, and a test that a retry with the same idempotency key succeeds. Say which part of the system should own the retry.
Exercise 3: Advanced (half day). Write a handler that validates a request body against the schema the client uses, then change the schema on one side only. Which test fails, and is that a good place to find the mismatch?
Related reading
In this course:
- Error, Loading and Empty States: the states this lesson tests.
- API Integration Basics: the calls and the data layer under test.
- Request Cancellation, Retries and Timeouts and Client Retries and Backoff: the policies a test can drive with overrides.
- API Contracts and Data Transformation: the shape checks the data layer applies.
Also in this module, in plain text because they are written in the same round: Unit and Component Testing, End-to-End Testing and Flaky Tests, and Contract Testing for Front Ends.
Official documentation
- MSW: Introduction: how requests are intercepted in the browser and in Node.
- MSW: Node.js integration:
setupServerand the listen, reset, close lifecycle. - MSW: setupServer.listen (version 1 docs): the
onUnhandledRequestoptions and default. - Vitest: Mocking requests: the MSW recommendation and strict setup.
- MDN: Window.fetch(): when the promise rejects and when it resolves.
- Testing Library: async utilities:
findBy,waitForand their defaults.