Lesson 11 of 11 · 13 min · Testing React
Mocking API calls in tests with MSW and Vitest
What you will learn
- Why unit tests should not call real APIs
- Mock a module or function with
vi.mock,vi.fnandvi.spyOn - Mock the network itself with Mock Service Worker (MSW)
- Test loading, success, empty and error states
- Reset mocks between tests and keep mocks realistic
In simple words
If a test calls the real server, it becomes slow, depends on the internet and on whatever data happens to be there, and can fail for reasons that have nothing to do with your code. Instead, the test pretends to be the server: when the component asks for orders, the test hands back a prepared answer, or a prepared failure. That makes tests fast, repeatable and able to check situations that are hard to create for real, such as a 500 error.
Words to know
- Mock: a stand-in for a real dependency that returns controlled results.
- Spy: a wrapper that records calls to a real function.
- MSW: Mock Service Worker, a library that intercepts network requests and answers them with mock responses.
- Fixture: prepared test data.
Why not call real APIs
- Speed: network calls take hundreds of milliseconds each.
- Reliability: the server, the network or the data may change or be down.
- Control: you cannot easily produce an error, a slow response or an empty list on demand.
- Safety and cost: tests could change real data or call paid services.
- Isolation: a component test should fail only when the component is wrong.
Real end-to-end tests (Playwright, Cypress) do call a real, test-environment server, and you should have a few. Unit and component tests mock.
The component under test
// api.ts
export type Order = { id: number; customer: string; amount: number };
export async function getOrders(): Promise<Order[]> {
const response = await fetch("/api/orders");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
// Orders.tsx
import { useEffect, useState } from "react";
import { getOrders, type Order } from "./api";
export function Orders() {
const [state, setState] = useState<
{ status: "loading" } | { status: "error" } | { status: "ready"; orders: Order[] }
>({ status: "loading" });
useEffect(() => {
getOrders()
.then((orders) => setState({ status: "ready", orders }))
.catch(() => setState({ status: "error" }));
}, []);
if (state.status === "loading") return <p>Loading...</p>;
if (state.status === "error") return <p role="alert">Could not load orders.</p>;
if (state.orders.length === 0) return <p>No orders yet.</p>;
return <ul>{state.orders.map((o) => <li key={o.id}>{o.customer}: {o.amount}</li>)}</ul>;
}
Option 1: mock the module
Replace your API function with a mock for the whole test file:
import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Orders } from "./Orders";
import { getOrders } from "./api";
vi.mock("./api"); // every export of ./api becomes a mock function
describe("Orders", () => {
beforeEach(() => vi.resetAllMocks()); // clear calls and implementations between tests
it("shows the orders", async () => {
vi.mocked(getOrders).mockResolvedValue([{ id: 101, customer: "Asha", amount: 1200 }]);
render(<Orders />);
expect(screen.getByText("Loading...")).toBeInTheDocument();
expect(await screen.findByText("Asha: 1200")).toBeInTheDocument();
});
it("shows an error when loading fails", async () => {
vi.mocked(getOrders).mockRejectedValue(new Error("boom"));
render(<Orders />);
expect(await screen.findByRole("alert")).toHaveTextContent("Could not load orders.");
});
it("shows an empty message", async () => {
vi.mocked(getOrders).mockResolvedValue([]);
render(<Orders />);
expect(await screen.findByText("No orders yet.")).toBeInTheDocument();
});
});
Vitest tools:
| Tool | Use |
|---|---|
vi.fn() |
create a mock function; mockReturnValue, mockResolvedValue, mockRejectedValue, mockImplementation |
vi.mock("./module") |
replace a whole module (the call is hoisted to the top of the file) |
vi.mock("./module", () => ({ fn: vi.fn() })) |
replace with a custom factory |
vi.spyOn(obj, "method") |
wrap a real method to record calls and optionally override it |
vi.mocked(fn) |
give TypeScript the mock's types |
vi.resetAllMocks(), vi.restoreAllMocks(), vi.clearAllMocks() |
reset between tests (or set mockReset: true in the config) |
expect(fn).toHaveBeenCalledWith(...), toHaveBeenCalledTimes(n) |
assert how the mock was used |
You can also spy on the global fetch: vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify(data), { status: 200 })). Module mocks are simple and quick, but they test your component against your idea of the API function, not the real HTTP layer, so bugs in URLs, headers, status handling or JSON parsing inside getOrders go unnoticed.
Option 2: mock the network with MSW
Mock Service Worker intercepts requests at the network level, so your real code (fetch, axios, TanStack Query) runs unchanged and receives mock responses. It tests more of the real behaviour and the same handlers can be reused in the browser during development and in other test tools.
npm install -D msw
// src/test/server.ts
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";
export const handlers = [
http.get("/api/orders", () =>
HttpResponse.json([{ id: 101, customer: "Asha", amount: 1200 }])
),
http.post("/api/orders", async ({ request }) => {
const body = (await request.json()) as { customerId: number };
return HttpResponse.json({ id: 102, customer: "Ravi", amount: 500, customerId: body.customerId }, { status: 201 });
}),
];
export const server = setupServer(...handlers);
// src/test/setup.ts (add to the setup file)
import { beforeAll, afterEach, afterAll } from "vitest";
import { server } from "./server";
beforeAll(() => server.listen({ onUnhandledRequest: "error" })); // fail on requests nobody mocked
afterEach(() => server.resetHandlers()); // remove per-test overrides
afterAll(() => server.close());
In jsdom, fetch needs absolute URLs for some setups; either use an absolute base URL in the code (http://localhost/api) or mock with the same pattern your app uses. Node.js 18 and later provide fetch globally, and MSW 2 works with it.
Per-test overrides model each scenario:
import { server } from "../test/server";
import { http, HttpResponse } from "msw";
it("shows an error when the server fails", async () => {
server.use(http.get("/api/orders", () => HttpResponse.json({ detail: "boom" }, { status: 500 })));
render(<Orders />);
expect(await screen.findByRole("alert")).toBeInTheDocument();
});
it("shows the empty state", async () => {
server.use(http.get("/api/orders", () => HttpResponse.json([])));
render(<Orders />);
expect(await screen.findByText("No orders yet.")).toBeInTheDocument();
});
it("shows the loading state while the request is pending", async () => {
server.use(http.get("/api/orders", async () => {
await new Promise((r) => setTimeout(r, 200)); // or delay() from msw
return HttpResponse.json([]);
}));
render(<Orders />);
expect(screen.getByText("Loading...")).toBeInTheDocument();
await screen.findByText("No orders yet.");
});
it("handles a network failure", async () => {
server.use(http.get("/api/orders", () => HttpResponse.error()));
render(<Orders />);
expect(await screen.findByRole("alert")).toBeInTheDocument();
});
Asserting on what was sent (the body of a POST): capture it in the handler, or assert on the result the UI shows:
let received: unknown;
server.use(http.post("/api/orders", async ({ request }) => {
received = await request.json();
return HttpResponse.json({ id: 1 }, { status: 201 });
}));
await user.click(screen.getByRole("button", { name: "Place order" }));
await screen.findByText("Order placed");
expect(received).toEqual({ customerId: 3, productIds: [1, 2] });
With TanStack Query
Create a fresh QueryClient per test with retries off, otherwise cached data leaks between tests and retries slow failures:
function renderWithClient(ui: React.ReactElement) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } });
return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
}
Then use MSW handlers as above. A shared client across tests is a classic source of flaky "works alone, fails together" behaviour.
Keeping mocks honest
- Make mock data realistic: copy the real API's shape and edge cases (null fields, long strings, empty arrays, Indian names and scripts, rupee amounts).
- Share fixtures and types with the real code, and generate them from an OpenAPI schema or the server's types where possible, so mocks fail to compile when the API changes.
- Do not over-mock: mock the network boundary (or the one API module), not every internal function or React hook.
- Add a few contract or end-to-end tests against a real test server, because mocks can drift away from reality.
- Never mock the thing you are testing.
- Fail on unhandled requests (
onUnhandledRequest: "error") so forgotten calls are noticed. - Reset state: reset handlers, mocks, storage and the query cache after each test.
Other things you will mock
- Browser APIs missing in jsdom:
window.matchMedia,IntersectionObserver,ResizeObserver,scrollTo,localStorage(jsdom has it),navigator.clipboard: stub them in the setup file withvi.stubGlobal. - Modules with side effects (analytics, maps, payment widgets):
vi.mockthem. - Time and randomness: fake timers,
vi.setSystemTime, seeded randomness. - Router hooks: use
MemoryRouterrather than mockinguseNavigate, unless you need to assert the call.
Common mistakes
- Letting tests hit the real network.
- Forgetting to reset mocks and handlers so tests affect each other.
- Mocking so much that the test proves nothing.
- Not testing error, empty and loading states.
- Sharing one
QueryClientacross tests. - Mock data that does not match the real API, hiding bugs.
- Using
vi.mockfor a module imported after the mock call is hoisted without a factory and gettingundefinedreturns (set return values per test).
Try it yourself
- Test the
Orderscomponent withvi.mock("./api")for success, error and empty. - Add MSW with a default handler and per-test overrides for 500, an empty array and a network error.
- Test a "Place order" form that sends a
POSTand assert on the request body and the confirmation message. - Switch the component to TanStack Query and write the tests with a per-test
QueryClient. - Turn on
onUnhandledRequest: "error"and fix a test that forgot a handler.
Check yourself
Why should unit tests not call real APIs?
They are slow, depend on network and server state, cannot easily produce errors, and may change real data; mocks make tests fast and deterministic.
What is the advantage of MSW over mocking an API module?
MSW intercepts at the network level, so the real request code (URLs, headers, parsing, error handling) runs and is tested, and the same handlers can be reused elsewhere.
Why use a new QueryClient for each test?
A shared client would keep cached data and retry settings between tests, causing tests to influence each other and become flaky.
What does onUnhandledRequest: "error" do?
It makes a test fail when the code makes a request that has no mock handler, so forgotten network calls are detected.
Interview questions
How do you test a component that fetches data?
Mock the network (with MSW) or the API module, render the component, assert the loading state, then wait with findBy for the success state; use per-test overrides for error and empty responses and check the request body for submissions.
What is the difference between a mock, a stub and a spy?
A stub returns canned answers, a mock also lets you verify how it was called, and a spy wraps a real function to record calls; in Vitest vi.fn() and vi.spyOn can serve all three roles.
What are the risks of mocking?
Mocks can drift from the real API and give false confidence, and over-mocking tests implementation rather than behaviour; mitigate with realistic shared fixtures, API schemas and a few end-to-end tests.
Summary
- Tests must not use the real network: mock at the module level with
vi.mockor, better, at the network level with MSW. - Test loading, success, empty and error states, request bodies and failures with per-test handler overrides.
- Reset mocks and handlers after each test; use a fresh
QueryClientand fail on unhandled requests. - Keep mocks realistic and complement them with a few end-to-end tests.
Going deeper
- Mock Service Worker documentation: handlers,
setupServerand testing recipes. - Vitest: Mocking:
vi.mock,vi.fn,vi.spyOn, timers and globals. - Testing Library: Guiding principles: why tests should resemble usage.
- TanStack Query: Testing: a fresh client per test and retries off.
See how much of this you can explain
A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.