API Mocking with MSW — Testing

MSW is a library that intercepts HTTP requests at the network level (when a request leaves your app), then answers them with responses you prepare. So your…

The user list test has passed (green) for months, because the fetch inside it is faked. Then a teammate replaces fetch with axios (another library for sending HTTP requests). The app works fine, but the test breaks, and its request goes out to the real internet.

MSW (Mock Service Worker) does not fake fetch. It fakes the server's answer. MSW is a library that intercepts HTTP requests at the network level: when a request leaves your app on its way to a server. Then MSW answers the request with a response you prepare. Nothing in your app code changes: it still calls fetch or axios as usual, and the answer from MSW looks the same as one from a real server. Picture the switchboard operator in an office. Staff call outside numbers as usual, but the operator intercepts calls to certain numbers and answers them with a prepared script. The staff don't need to change at all, only the operator gets a script. In this picture, the staff are your app code, the outside numbers are server addresses, the operator is MSW, and the script is the answers you prepare.

The code under test

This is the code to test, in two files:

// api.js
export async function fetchUsers() {
  const res = await fetch("https://api.shop.test/users");
  if (!res.ok) throw new Error(`Failed to load (${res.status})`);
  return res.json();
}

// users.js
export async function userNames() {
  const users = await fetchUsers();
  return users.map((u) => u.name);
}

fetchUsers fetches the users and throws "Failed to load" on a bad status, and userNames returns their names. The test has to run without a real api.shop.test server, and it must also be able to try a failing answer such as status 500 (an error on the server).

Handlers: the answer script

In MSW, that script is called a handler: a function that prepares the answer for one kind of request. The list of handlers usually has its own file:

// mocks/handlers.js
import { http, HttpResponse } from "msw";

export const handlers = [
  http.get("https://api.shop.test/users", () => {
    return HttpResponse.json([
      { id: 1, name: "Budi" },
      { id: 2, name: "Siti" },
    ]);
  }),
];

Using it in Vitest

The MSW server is made once, then started in a setup file: a file Vitest runs before each test file, listed in test.setupFiles:

// mocks/server.js
import { setupServer } from "msw/node";
import { handlers } from "./handlers";

export const server = setupServer(...handlers);

// test/setup.js, registered in test.setupFiles in vitest.config.js
import { beforeAll, afterEach, afterAll } from "vitest";
import { server } from "../mocks/server";

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

With that setup, the tests for userNames are written as usual. The second test changes the answer to status 500:

describe("userNames", () => {
  it("returns the names of all users", async () => {
    expect(await userNames()).toEqual(["Budi", "Siti"]);
  });

  it("throws an error when the server answers 500", async () => {
    server.use(http.get("https://api.shop.test/users", () => new HttpResponse(null, { status: 500 })));
    await expect(userNames()).rejects.toThrow("Failed to load (500)");
  });
});

server.use(...) adds a handler just for that test, and this handler is checked before the handlers from handlers.js. await expect(...).rejects.toThrow(...) checks that the Promise fails with that error. Async tests get a closer look in the next lesson, Testing Async Code.

How MSW picks an answer

MSW keeps a list of handlers. Each request is matched against that list, starting from the top handler. The first handler whose method and URL match is the one that answers.

When Handler list GET /users is answered with
At the start GET /users → 200 200, Budi and Siti
After server.use(...) GET /users → 500, then GET /users → 200 500
After resetHandlers() GET /users → 200 200 again
A GET /orders request nothing matches refused, the test fails

In the exercise, you write a small version of this yourself. It has three parts: adding a handler to an array (handlers.push(...)), finding the one that matches (handlers.find(...)) and running it or throwing an error when there is none, and emptying the array (handlers.length = 0).

Why at the network level

This table compares three ways to fake an API's answers in two situations: a mistyped URL in api.js, and the code moving from fetch to axios.

How it fakes Code that really gets tested URL in api.js mistyped Moving from fetch to axios
vi.mock("./api") only userNames, api.js never runs the test stays green, the bug is not caught the test is unaffected, because api.js was never tested
vi.spyOn(globalThis, "fetch") userNames and api.js, but the fake fetch answers any URL the test stays green, the bug is not caught breaks: axios doesn't go through fetch, so the request goes out to the internet
MSW everything, including the real fetch or axios the test fails, and MSW prints [MSW] Error: intercepted a request without a matching request handler keeps working unchanged

MSW works with any HTTP library (it is library-agnostic), because it intercepts the request at the network level, not the function. So when the code moves to axios, the MSW test keeps working, while the test that fakes fetch breaks.

⚠️ Handlers that don't answer, or answer wrong

TL;DR: MSW is a library that intercepts HTTP requests at the network level (when a request leaves your app), then answers them with responses you prepare. So your code that uses fetch or axios (another HTTP library) runs as it is, and only the answer is fake. A handler (a function that prepares the answer for one kind of request) is written http.get(url, () => HttpResponse.json(data)). In Vitest, setupServer(...handlers) from msw/node is set up with server.listen({ onUnhandledFrame: "error" }) in beforeAll, server.resetHandlers() in afterEach and server.close() in afterAll. With "error", a request with no handler fails the test. server.use(...) replaces the answer for one test, a status 500 (a server error) for example. Its advantage over vi.mock("./api"): your API code gets tested too, and the test works with any HTTP library.

⚡ A handler: the answer script

Write:

http.get("https://api.shop.test/users", () => {
  return HttpResponse.json([
    { id: 1, name: "Budi" },
    { id: 2, name: "Siti" },
  ]);
});

Meaning: MSW intercepts HTTP requests and answers them with responses you prepare. http.get(url, resolver) registers a handler (an answerer) for GET requests to that URL. The value the resolver (the second function) returns becomes the response: here a JSON response with two users. Your code still calls fetch as usual.

⚡ Used in Vitest

Write:

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

Meaning: server is MSW for tests in Node, made with setupServer(...handlers). listen starts intercepting, resetHandlers removes the extra handlers a previous test added, and close stops intercepting. With "error", a request with no handler fails the test right away.

⚡ Why at the network level

Guess first: the code moves from fetch to axios (another library for sending requests). What happens to the test that uses MSW?

It keeps working unchanged. MSW intercepts the request at the network level (when it leaves your app), not the function.

Meaning: That is the advantage of MSW over vi.mock("./api"), which replaces the whole API module with a stand-in: your API code gets tested too, and the test works with any HTTP library.

What you will learn