MSW (Mock Service Worker)

VerifiedSafe

Assists with intercepting network requests for API mocking using Mock Service Worker (MSW). Use when mocking REST or GraphQL APIs for unit tests, integration tests, or local development without modifying application code or running mock servers.

Sby Skills Guide Bot
TestingIntermediate
7/28/2026
Claude CodeCursorWindsurfCopilotCodex
#msw#api-mocking#rest#graphql#testing

Recommended for

Automated summary

This skill helps intercept network requests to mock REST and GraphQL APIs with Mock Service Worker, both in tests and for local development.

Strengths

  • Shares the same handlers between Node.js (setupServer) and the browser (setupWorker), keeping mocks consistent
  • Works with any HTTP client (fetch, axios, Apollo) without modifying application code
  • Explains per-test overrides via server.use() and resetHandlers() to prevent test pollution
  • Covers latency and error simulation with delay() and HttpResponse.error()

Limitations

  • Assumes familiarity with MSW's API; does not walk through initial installation or build configuration
  • Does not address advanced cases like streaming, WebSockets, or interception outside browser/Node contexts
  • Examples stay generic and do not provide complete copy-paste code
When to use it

Use it when you need to mock REST or GraphQL APIs in tests or local development without changing application code.

When not to use it

Avoid it if you need to mock WebSockets, streaming, or network calls outside the browser/Node scope MSW supports.

Security analysis

Safe
Quality score88/100

The skill provides guidance on using Mock Service Worker for API mocking in tests and development. It does not instruct destructive actions, exfiltration, or unsafe command execution. The only command mentioned is `npx msw init ./public`, which is a standard MSW setup command. No declared tools and no risky patterns.

No concerns found

How this analysis is made

Examples

Mock REST API for component tests
Set up MSW to mock my user API for React Testing Library tests, including GET /api/users, POST /api/users and GET /api/users/:id, plus an error-state override.
Mock GraphQL API in dev
Set up MSW to mock my GraphQL API during local development with setupWorker, handlers for GetPosts and CreatePost, and a 300ms delay.
Simulate network failures
Show me how to use server.use() with HttpResponse.error() and delay() to test how my app handles a failing API call.

name: msw description: >- Assists with intercepting network requests for API mocking using Mock Service Worker (MSW). Use when mocking REST or GraphQL APIs for unit tests, integration tests, or local development without modifying application code or running mock servers. Trigger words: msw, mock service worker, api mocking, test mocking, request handlers, setupServer. license: Apache-2.0 compatibility: "Requires Node.js 18+" metadata: author: terminal-skills version: "1.0.0" category: development tags: ["msw", "testing", "api-mocking", "rest", "graphql"]

MSW (Mock Service Worker)

Overview

MSW intercepts network requests at the service worker level (browser) or in-memory (Node.js) to mock REST and GraphQL APIs for tests and local development. It uses the same handlers for both environments, keeping mocks consistent, and works transparently with any HTTP client (fetch, axios, Apollo) without modifying application code.

Instructions

  • When setting up handlers, define REST handlers with http.get(), http.post(), etc. and GraphQL handlers with graphql.query() and graphql.mutation(), returning responses via HttpResponse.json().
  • When testing in Node.js, use setupServer(...handlers) with server.listen() before tests, server.resetHandlers() between tests, and server.close() after all tests.
  • When developing in the browser, use setupWorker(...handlers) and run npx msw init ./public to generate the service worker file, which intercepts requests visible in DevTools.
  • When overriding per test, use server.use() to add temporary handlers for error states or edge cases, which scope to the current test and reset afterward.
  • When simulating network issues, use delay(ms) for latency, HttpResponse.error() for failures, and custom status codes for error responses.
  • When organizing handlers, keep shared handlers in src/mocks/handlers.ts for reuse across test files and the dev server, with per-test overrides via server.use().

Examples

Example 1: Mock a REST API for component tests

User request: "Set up MSW to mock my user API for React Testing Library tests"

Actions:

  1. Define handlers in src/mocks/handlers.ts for GET /api/users, POST /api/users, and GET /api/users/:id
  2. Set up setupServer(...handlers) in the test setup file with beforeAll/afterEach/afterAll hooks
  3. Write component tests that render with data from the mock API
  4. Add per-test error overrides with server.use(http.get("/api/users", () => HttpResponse.json(null, { status: 500 })))

Output: Component tests with realistic API mocking, including happy path and error state coverage.

Example 2: Mock a GraphQL API for development

User request: "Set up MSW to mock my GraphQL API during local development"

Actions:

  1. Define GraphQL handlers for queries (GetPosts, GetUser) and mutations (CreatePost)
  2. Set up setupWorker(...handlers) in the browser entry point with conditional activation
  3. Add delay(300) to simulate realistic network latency
  4. Run npx msw init ./public and start the dev server

Output: A development environment with mocked GraphQL API visible in browser DevTools, with realistic latency.

Guidelines

  • Use MSW in both tests and development with the same handlers to keep mocks consistent.
  • Define handlers in a shared src/mocks/handlers.ts file for reuse across test files and the dev server.
  • Use server.use() for per-test overrides; keep the default happy path in shared handlers.
  • Always mock error states in tests to verify error handling works correctly.
  • Use delay() in development mocks to simulate real latency and catch loading state bugs.
  • Reset handlers after each test with afterEach(() => server.resetHandlers()) to prevent test pollution.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/msw-mock-service-worker-ms47vpfj' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/msw-mock-service-worker-ms47vpfj/download' --output '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md.part' && mv '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md.part' '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Environment declared by the author: Requires Node.js 18+

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md' && test -s '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/msw' && cp -R '.skill-downloads/msw-mock-service-worker-ms47vpfj' '.claude/skills/msw'

Cursor
test -f '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md' && test -s '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/msw' && cp -R '.skill-downloads/msw-mock-service-worker-ms47vpfj' '.cursor/skills/msw'

Codex
test -f '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md' && test -s '.skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/msw' && cp -R '.skill-downloads/msw-mock-service-worker-ms47vpfj' '.agents/skills/msw'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/msw-mock-service-worker-ms47vpfj'

openskills read 'msw-mock-service-worker-ms47vpfj'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/msw-mock-service-worker-ms47vpfj/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills