Mock Service Worker

MSW

Mock Service Worker (MSW) is an API mocking library for browsers and Node.js. Unlike other libraries that mock HTTP clients (like intercepting Axios or monkey-patching the global fetch), MSW operates directly at the network level.

How it Works

  • In the Browser: It registers a real Service Worker that intercepts outgoing requests right at the browser’s “Network” tab.
  • In Node.js (Tests): It uses native monkey patching on the http and https classes, intercepting requests at the lowest possible level without needing a Service Worker.

When to Use

  • UI Testing (Jest/Vitest/RTL): To simulate responses from real APIs in component tests, ensuring the component reacts exactly as it would in production without knowing the network is fake.
  • Development (API Mocking): When the Backend is not ready yet, you can develop the Frontend by hitting endpoints that are silently mocked by MSW in the browser.
  • Storybook: To provide controlled, consistent data for visual component stories.

Usage Example

First, we define our handlers (the fake endpoints):

import { http, HttpResponse } from "msw";

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

In your testing framework setup (e.g., Jest/Vitest), we initialize the server:

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

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

// Start before all tests
beforeAll(() => server.listen());
// Clear any dynamically added handlers in specific tests
afterEach(() => server.resetHandlers());
// Stop at the end
afterAll(() => server.close());

Related: frontend-testing-practices · testing-react-data-fetching

Built with Eleventy · search by Lunr.js