Mock Service Worker

2.13.4 · active · verified Tue Apr 21

Mock Service Worker (MSW) is a powerful and seamless library for intercepting and mocking REST and GraphQL API requests directly at the network level, in both browser and Node.js environments. Unlike traditional mocking libraries that patch client-side request utilities, MSW leverages the Service Worker API in browsers and a custom `http` interception module in Node.js. This approach allows applications to run against mock data without any code changes, making it ideal for consistent mocking across development, unit, integration, and end-to-end testing, as well as debugging. The current stable version is 2.13.4, with frequent minor and patch releases, often several times a month, indicating active development. Its key differentiator is providing deviation-free mocking by intercepting actual network requests, ensuring a high fidelity simulation of real API interactions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a browser-based Mock Service Worker to intercept and respond to HTTP GET and POST requests, followed by actual `fetch` calls that are intercepted by the mock server.

import { setupWorker, http, HttpResponse } from 'msw';

// Define handlers for your API requests
const handlers = [
  http.get('https://example.com/api/user/:userId', ({ params }) => {
    const { userId } = params;
    if (userId === '123') {
      return HttpResponse.json(
        { id: '123', name: 'John Doe', email: 'john.doe@example.com' },
        { status: 200 }
      );
    }
    return HttpResponse.json({ message: 'User not found' }, { status: 404 });
  }),
  http.post('https://example.com/api/users', async ({ request }) => {
    const newUser = await request.json();
    console.log('New user creation request:', newUser);
    return HttpResponse.json({ id: 'new-id', ...newUser }, { status: 201 });
  })
];

// Create a service worker instance
const worker = setupWorker(...handlers);

// Register the Service Worker in the browser
worker.start({
  onUnhandledRequest: 'warn' // Configure behavior for unhandled requests
});

console.log('MSW service worker started.');

// Example usage: Make a fetch request that will be intercepted by MSW
async function demonstrateMocking() {
  try {
    console.log('Fetching user 123...');
    const userResponse = await fetch('https://example.com/api/user/123');
    const userData = await userResponse.json();
    console.log('Fetched user (mocked):', userData);

    console.log('Creating a new user...');
    const createUserResponse = await fetch('https://example.com/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: 'Jane Smith', email: 'jane.smith@example.com' })
    });
    const newUserData = await createUserResponse.json();
    console.log('Created user (mocked):', newUserData);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

demonstrateMocking();

view raw JSON →