Skip to the content

Lesson 185 of 296

Mocking fetch and the network

What you will learn

  • Why tests must not call real APIs
  • Mocking fetch with vi.spyOn
  • Mock Service Worker (MSW)
  • Testing loading, success and error states
  • Fake timers for debounce and delays
  • Mocking modules
On this page

Why mock?

Tests that call real APIs are slow, flaky (they fail when the network or the API is down), can change real data, and cannot easily test errors. So tests replace the network with a mock: a fake that returns the response you choose.

WordMeaning
MockA fake replacement that you can check (was it called? with what?)
StubA fake that returns fixed answers
SpyWraps a real function to record calls, optionally replacing its behaviour

The component under test

A user list that loads from an API:

TSX
import { useEffect, useState } from "react";

type User = { id: number; name: string };

export function UserList() {
  const [state, setState] = useState<
    { status: "loading" } | { status: "error" } | { status: "success"; users: User[] }
  >({ status: "loading" });

  useEffect(() => {
    let ignore = false;
    fetch("https://api.example.com/users")
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json() as Promise<User[]>;
      })
      .then((users) => {
        if (!ignore) setState({ status: "success", users });
      })
      .catch(() => {
        if (!ignore) setState({ status: "error" });
      });
    return () => {
      ignore = true;
    };
  }, []);

  if (state.status === "loading") return <p>Loading users...</p>;
  if (state.status === "error") return <p role="alert">Could not load users.</p>;
  if (state.users.length === 0) return <p>No users yet.</p>;
  return (
    <ul aria-label="Users">
      {state.users.map((u) => <li key={u.id}>{u.name}</li>)}
    </ul>
  );
}

Option 1: spy on fetch

Replace the global fetch for one test:

TSX
import { afterEach, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";

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

it("shows users from the API (fetch spy)", async () => {
  const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(
    new Response(JSON.stringify([{ id: 1, name: "Aisha" }]), { status: 200 })
  );

  render(<UserList />);

  expect(screen.getByText("Loading users...")).toBeInTheDocument();
  expect(await screen.findByText("Aisha")).toBeInTheDocument();
  expect(fetchSpy).toHaveBeenCalledWith("https://api.example.com/users");
});
  • mockResolvedValue makes the fake return a resolved Promise with a real Response object.
  • vi.restoreAllMocks() puts the real fetch back after each test, so tests do not affect each other.

This is quick, but it ties the test to how you fetch: switch to axios or TanStack Query and the test breaks, even though the behaviour is the same.

Mock Service Worker (MSW) intercepts requests at the network level. Your component, whatever library it uses (fetch, axios, TanStack Query), makes a normal request, and MSW answers it. The same handlers can be reused in tests, in the browser during development, and in Storybook.

TSX
import { afterAll, afterEach, beforeAll, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import { http, HttpResponse, delay } from "msw";
import { setupServer } from "msw/node";

const server = setupServer(
  http.get("https://api.example.com/users", () =>
    HttpResponse.json([
      { id: 1, name: "Aisha" },
      { id: 2, name: "Ben" }
    ])
  )
);

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

it("renders the list of users", async () => {
  render(<UserList />);
  const list = await screen.findByRole("list", { name: "Users" });
  expect(list.querySelectorAll("li")).toHaveLength(2);
  expect(screen.getByText("Ben")).toBeInTheDocument();
});

it("shows an error when the API fails", async () => {
  server.use(http.get("https://api.example.com/users", () => new HttpResponse(null, { status: 500 })));
  render(<UserList />);
  expect(await screen.findByRole("alert")).toHaveTextContent("Could not load users.");
});

it("shows an empty state", async () => {
  server.use(http.get("https://api.example.com/users", () => HttpResponse.json([])));
  render(<UserList />);
  expect(await screen.findByText("No users yet.")).toBeInTheDocument();
});

it("shows loading while the request is slow", async () => {
  server.use(
    http.get("https://api.example.com/users", async () => {
      await delay(200);
      return HttpResponse.json([{ id: 3, name: "Chen" }]);
    })
  );
  render(<UserList />);
  expect(screen.getByText("Loading users...")).toBeInTheDocument();
  expect(await screen.findByText("Chen")).toBeInTheDocument();
});

How it works:

  • setupServer (from msw/node) intercepts requests in Node.js. In the browser, setupWorker uses a real Service Worker.
  • server.listen({ onUnhandledFrame: "error" }) makes any request without a handler fail loudly, so tests never call a real API by accident. (In MSW version 2 this option was called onUnhandledRequest; version 3 renamed it because it also covers WebSocket connections.)
  • server.use(...) overrides a handler for one test (error, empty, slow). resetHandlers() removes overrides after each test.
  • One test per state: loading, success, empty, error. This is exactly what interviewers want to see.

You may see old tutorials using rest.get(...) and res(ctx.json(...)): that is the MSW version 1 API. Versions 2 and 3 use http.get and HttpResponse.

Fake timers

Code that waits (debounce, timeouts, polling) would make tests slow. Fake timers let the test move time forward instantly:

TSX
import { it, expect, vi } from "vitest";

function debounce<A extends unknown[]>(fn: (...args: A) => void, ms: number) {
  let id: ReturnType<typeof setTimeout> | undefined;
  return (...args: A) => {
    clearTimeout(id);
    id = setTimeout(() => fn(...args), ms);
  };
}

it("only calls once after the user stops typing", () => {
  vi.useFakeTimers();
  const search = vi.fn();
  const debounced = debounce(search, 300);

  debounced("r");
  debounced("re");
  debounced("rea");
  vi.advanceTimersByTime(299);
  expect(search).not.toHaveBeenCalled();

  vi.advanceTimersByTime(1);
  expect(search).toHaveBeenCalledTimes(1);
  expect(search).toHaveBeenCalledWith("rea");
  vi.useRealTimers();
});

With user-event and fake timers together, create the user with userEvent.setup({ advanceTimers: vi.advanceTimersByTime }).

Mocking modules

To replace a whole module (for example an analytics library or a date helper):

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

Use this sparingly: the more you mock, the less your test proves. Mock at the edges (network, time, randomness, browser APIs not in jsdom), not your own components.

How to say it in an interview

"Tests should not call real APIs because that is slow, flaky and cannot easily test failures. I can spy on fetch with vi.spyOn and return a Response, but I prefer Mock Service Worker, which intercepts at the network level so tests do not depend on which HTTP library I use. I make unhandled requests fail with an error, define default handlers, override them per test with server.use for error, empty and slow cases, and reset after each test. For debounce and polling I use fake timers, and I mock only at the edges like network, time and randomness."

Key words

WordMeaning
MockA fake replacement you can inspect
SpyRecords calls to a real function, optionally replacing it
Flaky testA test that sometimes passes and sometimes fails without code changes
MSWMock Service Worker: mocks APIs at the network level
HandlerAn MSW rule that answers a matching request
Fake timersTest tools that control time (vi.useFakeTimers)

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.