Skip to content
FrontDepth, Home

Testing

Mocking the network and modules

How to fake the network and modules without ending up testing your mocks: choosing the seam, Mock Service Worker handlers and per-test overrides for loading and error states, the cost of stubbing fetch, vi.mock hoisting and partial mocks, ES module limits on spying, and contract drift.

MiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Middle level.

MiddleConcept

Choosing the seam: where to mock

A replaces something real, and the place where the test cuts the real code off is the seam. For code that loads data there are three common seams:

Text
TaskList → useTasks() → api.getTasks() → fetch() → network → server

1. vi.mock("./api")         replaces api.getTasks()
2. vi.stubGlobal("fetch")   replaces fetch()
3. an MSW handler           replaces the server's answer

The lower the seam, the more of your own code runs in the test. Mock your api module (seam 1) and the test never runs the code that builds the URL, sets headers, serialises the body, checks response.ok, parses JSON and turns failures into errors, which is the code most likely to be wrong. The test also breaks when you refactor the wrapper (rename getTasks, change its arguments) although the screen behaves exactly as before.

Mocking at the network boundary (seam 3) replaces only what is really outside your app: the server. The component, the hook, the wrapper and the real fetch all run; the test only decides what the server answers. A refactor that keeps the same requests and the same UI keeps the tests green. This is what Mock Service Worker (MSW) is built for, and it is what Vitest's guide recommends for mocking requests.

A rule of thumb: mock what you do not own, at the point where it enters your code. For HTTP that point is the request leaving your code, not your own wrapper around fetch.

A is still the right tool when the dependency is not the network you are testing:

  • an SDK with side effects you do not want in a test: analytics, error reporting, a payment widget;
  • a library that is heavy or does not work in jsdom: a map, a WebGL chart;
  • a value the test must control: a feature-flag client, an ID generator.

The seam also decides what a red test means. When a network-level test fails, behaviour the user can see has changed. When a test that mocks your own module fails, often only the call between two of your files has changed.

Stubbing the global fetch (seam 2) sits in between: it runs your wrapper, but it freezes the way the wrapper calls fetch. Its costs are listed in the section on vi.stubGlobal.

MiddleFramework

Mock Service Worker: handlers and the test server

MSW describes the server's answers as request handlers: an HTTP method, a URL pattern and a resolver function that returns a response.

TypeScript
// src/mocks/handlers.ts
import { http, HttpResponse } from "msw/http";

export const API = "https://api.example.com";

export const handlers = [
  http.get(`${API}/tasks`, () => {
    return HttpResponse.json([
      { id: "t1", title: "Write the release notes", done: false },
      { id: "t2", title: "Review the login page", done: true },
    ]);
  }),

  http.post(`${API}/tasks`, async ({ request }) => {
    const body = (await request.json()) as { title?: string };
    if (!body.title) {
      return HttpResponse.json({ message: "Title is required" }, { status: 400 });
    }
    return HttpResponse.json({ id: "t3", title: body.title, done: false }, { status: 201 });
  }),
];

The resolver receives the real Request (request), the path parameters (params, for a pattern like /tasks/:id) and cookies. HttpResponse.json(body, init) builds a response with a JSON body; init takes status and headers, like the Response constructor.

In Vitest (Node), setupServer from msw/node turns the handlers on. Despite the name it opens no port: it intercepts outgoing requests inside the test process, so your code's real fetch call runs and receives the handler's response.

TypeScript
// src/mocks/node.ts
import { setupServer } from "msw/node";
import { handlers } from "./handlers";

export const server = setupServer(...handlers);
TypeScript
// vitest.setup.ts (listed in test.setupFiles)
import "@testing-library/jest-dom/vitest";
import { afterAll, afterEach, beforeAll } from "vitest";
import { server } from "./src/mocks/node";

beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
  • listen() starts the interception and close() stops it.
  • resetHandlers() removes the handlers a test added with server.use() and keeps the initial list.
  • onUnhandledFrame: "error" prints an error and stops a request that no handler matches. The default, "warn", prints a warning and lets the request through, so a typo in a URL can quietly send a test to a real server.

These are MSW 3's names. MSW 2 exported http and HttpResponse from msw and called the option onUnhandledRequest; MSW 3 renamed it because it now also covers WebSocket connections.

In the browser the same handlers run through setupWorker from msw/browser, which registers a Service Worker (npx msw init <PUBLIC_DIR> --save copies its script into your public folder). It serves local development against an unfinished API, Storybook and browser test runners. Await worker.start() before rendering, or the first requests can go out before the worker is ready.

MiddleExample

Testing loading, error and slow responses

TaskList fetches ${API}/tasks and shows "Loading tasks..." with role="status", then the list, "No tasks yet." or an alert. The default handler covers the happy path; every other state is one server.use() call away:

TSX
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
import { http, HttpResponse } from "msw/http";
import { delay } from "msw/utils/delay";
import { API } from "../mocks/handlers";
import { server } from "../mocks/node";
import { TaskList } from "./TaskList";

test("shows the tasks", async () => {
  render(<TaskList />);
  expect(await screen.findByText("Write the release notes")).toBeInTheDocument();
});

test("shows the empty state", async () => {
  server.use(http.get(`${API}/tasks`, () => HttpResponse.json([])));
  render(<TaskList />);
  expect(await screen.findByText("No tasks yet.")).toBeInTheDocument();
});

test("shows an error when the server fails", async () => {
  server.use(
    http.get(`${API}/tasks`, () => HttpResponse.json({ message: "Down" }, { status: 500 })),
  );
  render(<TaskList />);
  expect(await screen.findByRole("alert")).toHaveTextContent("Could not load tasks");
});

test("shows an error when the network fails", async () => {
  server.use(http.get(`${API}/tasks`, () => HttpResponse.error()));
  render(<TaskList />);
  expect(await screen.findByRole("alert")).toBeInTheDocument();
});

test("keeps the loading state while the server is silent", () => {
  server.use(
    http.get(`${API}/tasks`, async () => {
      await delay("infinite");
      return HttpResponse.json([]);
    }),
  );
  render(<TaskList />);
  expect(screen.getByRole("status")).toHaveTextContent("Loading tasks");
});
  • server.use() prepends handlers, and MSW uses the first handler that returns a response, so the override wins for this test only; resetHandlers() in afterEach removes it. A handler with { once: true } answers one matching request and is then ignored: handy for "the first request fails, the retry succeeds".
  • A 500 does not reject fetch. The promise resolves with response.ok === false; only a network error rejects, and HttpResponse.error() makes fetch reject with a TypeError. These are two code paths, so test both.
  • delay() without an argument waits a realistic random time in the browser, but in Node that implicit delay is skipped to keep tests fast. delay(ms) waits exactly that long, and delay("infinite") never answers.

Assert on what the user sees, not on "the request was made": MSW's docs discourage request assertions as implementation details. If the body matters, check it in the handler and answer 400, as the POST /tasks handler does; a wrong body then shows up on the screen.

MiddlePitfalls

Stubbing fetch with vi.stubGlobal

The quick alternative to MSW replaces fetch itself:

TypeScript
import { afterEach, expect, it, vi } from "vitest";
import { getTasks } from "./api";

afterEach(() => {
  vi.unstubAllGlobals();
});

it("loads the tasks", async () => {
  const fetchMock = vi.fn(async () =>
    Response.json([{ id: "t1", title: "Write the release notes", done: false }]),
  );
  vi.stubGlobal("fetch", fetchMock);

  const tasks = await getTasks();

  expect(tasks).toHaveLength(1);
  expect(fetchMock).toHaveBeenCalledWith("https://api.example.com/tasks");
});

vi.stubGlobal(name, value) changes a global: globalThis.fetch, and window.fetch under jsdom or happy-dom. vi.unstubAllGlobals() restores the original values, and the unstubGlobals: true config option calls it before each test. A plain assignment (globalThis.fetch = ...) works too, but then unstubAllGlobals cannot restore it, and the fake leaks into every later test in the file.

The test passes, but it now describes how the code calls fetch rather than what the code does:

  • The call shape is frozen. toHaveBeenCalledWith(url) fails as soon as the code passes a second argument (headers, an AbortSignal), builds a Request object or moves to a request library, although nothing changed for the user.
  • The response is whatever you typed. A hand-made { json: async () => data } has no ok, status or headers, so error handling never runs the way it would with a real response. Response.json(), as above, at least builds a real Response.
  • One stub serves every request. A screen that loads /tasks and /me needs a chain of mockResolvedValueOnce calls in the exact call order. Reorder two requests and each gets the other's body.
  • Other ways of sending are not covered. Code that uses XMLHttpRequest or navigator.sendBeacon goes past the stub.

MSW avoids all four: handlers match by method and URL, answer with real responses, serve each endpoint separately and do not care how the request was made.

vi.stubGlobal is the right tool for globals that are not the network and that the test environment lacks or the test must control: IntersectionObserver, ResizeObserver and matchMedia, which jsdom does not implement, or innerWidth for a layout branch. Pair it with unstubGlobals: true so each test starts from the real values.

MiddleFramework

vi.mock: replacing a module

vi.mock(path, factory?) replaces a module: every import of that path, in the test and in the code under test, gets the replacement. Here completeTask sends PATCH /tasks/:id (answered by MSW) and reports an analytics event, which the test must not send for real:

TypeScript
// tasks.test.ts
import { expect, it, vi } from "vitest";
import { trackEvent } from "./analytics";
import { completeTask } from "./tasks";

vi.mock("./analytics", () => ({
  trackEvent: vi.fn(),
}));

it("reports the completed task", async () => {
  await completeTask("t1");
  expect(trackEvent).toHaveBeenCalledWith("task_completed", { id: "t1" });
});

Asserting a call is fine here: the analytics event is a one-way side effect with nothing on screen to check.

Hoisting. vi.mock is moved to the top of the file and runs before all imports, so it does not matter that it is written below them. Vitest rewrites the file's static imports into dynamic ones that wait for the mock to be registered. The consequence: the factory cannot use variables declared in the file outside it, because they do not exist yet when it runs. Create shared values with vi.hoisted, which is hoisted as well:

TypeScript
const { trackEvent } = vi.hoisted(() => ({ trackEvent: vi.fn() }));
vi.mock("./analytics", () => ({ trackEvent }));

Inside a test, a describe or a function, the call would not run where it is written; Vitest 5 throws an error there (earlier versions only warned). vi.doMock is the variant that is not hoisted.

The factory's object is the module. Exports it leaves out are not there, and a default export needs a default key. Without a factory Vitest uses a file of the same name in a __mocks__ folder; if there is none, it automocks the real module: functions become mocks returning undefined, arrays become empty, primitives stay as they are, objects are deeply cloned.

Partial mocks keep the real module and replace one export:

TypeScript
vi.mock(import("./analytics"), async (importOriginal) => {
  const actual = await importOriginal();
  return { ...actual, trackEvent: vi.fn() };
});

Passing import("./analytics") instead of a string gives importOriginal the module's type and checks the factory's return value against it. vi.importActual(path) loads the real module the same way anywhere in the file. To configure the mock per test with types, wrap it: vi.mocked(trackEvent).mockReturnValue(...); vi.mocked only changes the type and returns the same function.

MiddlePitfalls

Resetting between tests

Every mock is state, and state left over from one test changes the next. The symptom is a test that passes alone and fails in the full run, or the reverse; such tests become as soon as the order changes. What can leak, and what resets it:

  • MSW runtime handlers. A server.use() override stays until server.resetHandlers(); without it in afterEach, the error state set up in one test is what the next test gets.
  • Stubbed globals. vi.stubGlobal stays until vi.unstubAllGlobals(), or set unstubGlobals: true.
  • Mock implementations. Vitest 5 clears call history before every test by default (clearMocks is now true), but an implementation set with mockReturnValue or mockImplementation stays. mockReset: true resets implementations before each test; restoreMocks: true puts back the originals of spies made with vi.spyOn.
  • State inside modules. A module is evaluated once per test file, so a cache in your API client, a memoised user or a shared data-fetching client survives from one test to the next. Create a fresh instance per test (export a factory instead of a singleton) or clear it in afterEach.

One config turns most of this on for every file:

TypeScript
// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    environment: "jsdom",
    globals: true,
    setupFiles: ["./vitest.setup.ts"],
    mockReset: true,
    restoreMocks: true,
    unstubGlobals: true,
  },
});

With mockReset on, set each mock's behaviour in the test or in beforeEach, next to the case that needs it, instead of once at the top of the file. That is also easier to read: the test shows the answer it depends on.

A good check: run a single test with .only, then the whole file. If the results differ, some state is shared. Find it and reset it; adding retries only hides it.

SeniorConcept

ES modules, live bindings and spying on exports

An import is a live, read-only view of the exporting module's variable, not a copy (the ES modules topic covers this). Two consequences matter for mocking.

A namespace object cannot be patched. import * as analytics from "./analytics" gives a module namespace object whose properties cannot be reassigned or redefined; analytics.trackEvent = fake throws a TypeError in a module. vi.spyOn(analytics, "trackEvent") still works in Vitest's Node, jsdom and happy-dom environments because Vitest's module runner allows it, on what its docs call "a seemingly ES Module", with a warning that this might change. In Browser Mode, where modules are native, it fails: the namespace "is sealed and can't be reconfigured". The form that works everywhere is vi.mock("./analytics", { spy: true }): Vitest automocks the module but keeps each export's real implementation, so you can assert calls while the real code runs.

Calls inside the same module are not intercepted.

TypeScript
// analytics.ts
export function trackEvent(name: string, data: object) {
  navigator.sendBeacon("/events", JSON.stringify({ name, data }));
}

export function trackTaskCompleted(id: string) {
  trackEvent("task_completed", { id });
}

A spy or a mock of trackEvent changes what other modules see when they import it. trackTaskCompleted calls its own local binding directly, so it keeps calling the real function. Vitest's mocking guide lists this pitfall: such a function cannot be mocked from the outside "because it is referenced directly". Two fixes:

  • move the function you want to replace into its own module, so the caller imports it and vi.mock can swap it;
  • pass it in (dependency injection): trackTaskCompleted(id, send = trackEvent), and the test passes its own send.

Why vi.mock is not affected by any of this. It does not patch a module after it is loaded. It registers the replacement in the module registry before anything imports the module, which is why the call is hoisted and the file's imports are rewritten into dynamic ones. Every importer then binds to the replacement from the start; nothing needs to be reassigned.

This also explains a common surprise: a spy created after the code under test captured a reference (const send = analytics.trackEvent at module level, or a callback registered at startup) does not see those calls. vi.spyOn only records calls made through the property after the spy was installed.

SeniorFramework

Changing a module mock per test

vi.mock runs once per file, before the imports. That covers most needs; there are two ways to vary a module between tests, from the simpler:

1. Change the mock's behaviour. If the module exports functions, mock them once and set the return value in each test:

TypeScript
import { isEnabled } from "./flags";

vi.mock("./flags", () => ({ isEnabled: vi.fn() }));

it("shows the new editor when the flag is on", () => {
  vi.mocked(isEnabled).mockReturnValue(true);
  render(<Editor />);
  expect(screen.getByRole("heading", { name: "New editor" })).toBeInTheDocument();
});

2. Re-evaluate the module. If the code reads the dependency while the module is evaluated (const newEditor = flags.newEditor at the top of editor.ts), changing the mock later has no effect: the value was read once. Then use vi.doMock, which is not hoisted and applies to the next dynamic import(), together with vi.resetModules() so the module is evaluated again:

TypeScript
beforeEach(() => {
  vi.resetModules();
});

it("uses the new editor when the flag is on", async () => {
  vi.doMock("./flags", () => ({ newEditor: true }));
  const { editorKind } = await import("./editor");
  expect(editorKind()).toBe("new");
});

it("keeps the old editor when the flag is off", async () => {
  vi.doMock("./flags", () => ({ newEditor: false }));
  const { editorKind } = await import("./editor");
  expect(editorKind()).toBe("old");
});

Static imports at the top of the file were evaluated before vi.doMock ran, so the module under test must be imported dynamically after it. vi.resetModules() clears the module cache but not the mocks registry; vi.doUnmock(path) removes a registered mock.

Option 2 works, but it is a sign of a design that is hard to test: a module that reads configuration at import time. Reading the flag inside the function (option 1) or passing it in as a prop or argument makes the test, and the code, simpler.

Keep the mocks honest. Whatever the technique, a mock only says what the module returned on the day you wrote it. Prefer factories that start from importOriginal() and replace only the parts with side effects, so the rest of the module keeps its real behaviour, and use types (vi.mock(import("./flags"), ...)) so the compiler notices when the real module changes shape.

SeniorConcept

Contract drift: when mocks stop matching the API

A mock is a copy of the API's behaviour taken on the day it was written. When the backend renames done to completed, the handlers still answer done, every test passes, and production shows every task as open. This is contract drift: the more realistic the mocks look, the more confident and the more wrong the tests become.

Ways to catch it, roughly from the cheapest:

Type the mocks with the API's types. If the client's types are generated from the API's schema (for example an OpenAPI document the backend publishes), a renamed field becomes a type error in the fixtures. MSW handlers take generic types in the order Params, RequestBodyType, ResponseBodyType, and HttpResponse.json() must then match the response type:

TypeScript
import type { Task } from "../api/types";

http.patch<{ id: string }, { done: boolean }, Task>(`${API}/tasks/:id`, async ({ params, request }) => {
  const { done } = await request.json();
  return HttpResponse.json({ id: params.id, title: "Write the release notes", done });
});

Run fixtures through the app's schema. If the client validates responses at the boundary (), for example with a Zod schema, parse the fixtures with the same schema in a test. A fixture the real client would reject then fails in CI instead of hiding a broken contract.

Build fixtures in one place. Factories like makeTask({ done: true }) mean a shape change is one edit, not forty handlers that each copied the object.

Contract tests. Martin Fowler describes a contract test as one that runs against the real service (a test instance) and checks that a test double is an accurate representation of it, caring more about the format of the data than its values. They do not have to run on every commit; their schedule follows the service's changes.

A few real end-to-end checks. Keep the most important journeys as against a real backend, unmocked. They are slow, so there are few of them, but a broken contract then fails somewhere before users see it.

One set of handlers. If unit tests, Storybook and local development (through setupWorker) each keep their own fake API, there are three copies to drift. Share one handlers module.

The goal is not to stop mocking. Fast tests with mocks give feedback in seconds; the checks above make sure the mocks still describe the API that runs in production.

SeniorInterview tips

Interview tips

A 30-second answer. "I mock at the network boundary, usually with MSW: handlers describe what the server answers, setupServer intercepts requests in Node, and the real fetch, wrapper and component all run. I override a handler per test with server.use() to cover errors, empty data and slow responses, reset handlers after each test, and make unhandled requests fail. I use vi.mock for modules that are not the network, like analytics or feature flags, knowing it is hoisted and replaces the module for every importer. And I watch for contract drift: typed fixtures, the same schema the app uses, and a few unmocked E2E tests."

Questions you are likely to get

  • Why not mock fetch, or your own API module? Both cut the test off above the code most likely to be wrong, and both tie it to how the code calls things. A network-level mock survives refactors that keep behaviour.
  • How do you test an error state? server.use() with a 500 and with HttpResponse.error(); explain that a 500 resolves fetch with ok: false while a network error rejects it.
  • What does it mean that vi.mock is hoisted? It runs before the imports; the factory cannot use the file's variables except those made with vi.hoisted; a nested vi.mock throws in Vitest 5; vi.doMock is the non-hoisted variant.
  • Why does my spy on a named export not see the call? The caller is in the same module and uses its local binding, or the module system does not allow redefining namespace properties. Use vi.mock with { spy: true }, split the module, or inject the dependency.
  • How do you know the mocks still match the backend? Generated types, shared schema validation, contract tests, a few real E2E checks.

Mistakes that cost points

  • Asserting that a request was sent instead of checking what the user sees.
  • Mocking everything a component imports; the test then checks the mocks, not the code.
  • Forgetting resetHandlers() or unstubAllGlobals() and blaming the "flaky" result on the runner.
  • Leaving onUnhandledFrame (onUnhandledRequest in MSW 2) at its default, so a wrong URL silently reaches the real network.

Senior signal

Explain the trade-off rather than a rule: which seam you would choose for a given dependency and why, what a failure at that seam tells you, and how you keep the fakes from drifting away from production. Mention that the same handlers can serve tests, Storybook and local development, so one fake API is maintained instead of three.

MiddleReview checklist

What to check when reviewing mocks

Use this list when you review tests that mock the network or modules in code you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. Mistakes in mocks rarely fail a test; they make tests pass while the real app breaks, or make them fail for reasons unrelated to the change.

  • Is the network mocked at the network boundary? A vi.mock of the team's own API wrapper or a vi.stubGlobal("fetch") skips URL building, status checks and parsing; prefer MSW handlers, and check that the code under test still calls the real fetch.
  • Do unhandled requests fail? Look for onUnhandledFrame: "error" (onUnhandledRequest in MSW 2) in the listen() call; with the default "warn", a wrong URL passes through to the real network and the test depends on it.
  • Is every override reset after the test? server.resetHandlers() in afterEach, vi.unstubAllGlobals() or unstubGlobals: true, and restoreMocks or mockReset for spies and implementations. Run the file with and without .only on one test: different results mean leaked state.
  • Are error and loading states tested, and with the right failure? A 500 needs response.ok handling, a network error (HttpResponse.error()) a catch; one test of each, plus an empty response, shows whether the code handles them.
  • Does the test assert on what the user sees? expect(fetch).toHaveBeenCalledWith(...) or a check that a handler was hit tests the call, not the result; validate request bodies in the handler and assert on the screen instead.
  • Will the module mock actually be used? vi.mock must be at the top level, with no outer variables in the factory except vi.hoisted ones; a spy on an export does not see calls made inside the same module.
  • Do the fixtures match the real API? They should be typed with the API's types or parsed with the app's schema, built by shared factories, and backed by at least one unmocked E2E test of the journey.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions