Contact Us
Webflow Premium Partner Ehab Fayez
Back to Agent Skills
Development & Testing

Mock Service Worker (MSW)

Intercept network requests at the service worker level for seamless API mocking in tests and development.

Claude Code Codex Copilot Cursor Gemini CLI Windsurf

Overview

Mock Service Worker (MSW) intercepts HTTP requests at the network level using a Service Worker in the browser and a request interceptor in Node.js. Unlike mocking fetch or axios directly, MSW works with any HTTP client and provides realistic network behavior including delays, errors, and streaming responses. AI agents can define handlers that match your actual API contracts.

Your AI agent can write request handlers using MSW's intuitive API: http.get, http.post, and other methods that mirror your REST endpoints or GraphQL operations. The handlers return mock responses that your components consume exactly as they would real API responses. This means your tests and development environment use the same code, just with different data sources.

MSW is especially powerful for testing because it does not require any changes to your application code. Your AI agent can set up handlers for happy paths, error states, loading states, and edge cases. It can configure MSW for both browser-based Storybook stories and Node.js-based Jest/Vitest tests, providing a unified mocking strategy across your entire test suite.

Who Is This For?

  • Frontend developers mocking API responses during development without a backend
  • Test engineers creating realistic network scenarios for integration tests
  • Teams testing error handling by simulating server failures and timeouts
  • Storybook users mocking API dependencies for component stories

Installation

Setup for Claude Code
npm install -D msw
npx msw init public/
Claude Code generates request handlers and test setups

Configuration

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

export const handlers = [
  http.get("/api/users", () => {
    return HttpResponse.json([
      { id: 1, name: "Alice" },
      { id: 2, name: "Bob" },
    ]);
  }),
  http.post("/api/login", async ({ request }) => {
    const body = await request.json();
    return HttpResponse.json({ token: "mock-jwt-token" });
  }),
];