/web-mocks-msw
MSW handlers, browser/server workers, test data. Use when setting up API mocking for development or testing, creating mock handlers with variants, or sharing mocks between browser and Node environments.
$ npx -y skills add agents-inc/skills --skill web-mocks-msw --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.
- You can call itInvoke it directly when you want it.
- Slash command
/web-mocks-msw
Context preview
The summary Claude sees to decide when to auto-load this skill.
MSW handlers, browser/server workers, test data. Use when setting up API mocking for development or testing, creating mock handlers with variants, or sharing mocks between browser and Node environments.
SKILL.md
web-mocks-msw.SKILL.mdname: web-mocks-msw
description: MSW handlers, browser/server workers, test data. Use when setting up API mocking for development or testing, creating mock handlers with variants, or sharing mocks between browser and Node environments.
API Mocking with MSW
> **Quick Guide:** Handlers with variant switching (default, empty, error). Shared between browser (dev) and Node (tests). Separate mock data from handlers for reusability. Type-safe using your API's generated types. Use `setupWorker` (browser) and `setupServer` (Node) -- never swap them.
**Detailed Resources:**
- [examples/core.md](examples/core.md) - Mock data, variant handlers, server worker, per-test overrides, runtime switching, network simulation
- [examples/browser.md](examples/browser.md) - Browser worker setup, SPA/SSR integration
- [reference.md](reference.md) - Decision frameworks, red flags, anti-patterns
---
<critical_requirements>
CRITICAL: Before Using This Skill
**(You MUST separate mock data from handlers - handlers in `handlers/`, data in `mocks/`)**
**(You MUST use `setupWorker` for browser/development and `setupServer` for Node/tests - NEVER swap them)**
**(You MUST reset handlers after each test with `server.resetHandlers()` in `afterEach`)**
**(You MUST use named constants for HTTP status codes and delays - NO magic numbers)**
</critical_requirements>
---
**Auto-detection:** MSW, msw, mock handlers, mock data, API mocking, setupWorker, setupServer, http.get, HttpResponse
**When to use:**
- Mocking API responses during development before backend is ready
- Testing different API scenarios (success, empty, error states)
- Sharing the same mock definitions between browser dev and Node test environments
- Simulating network conditions (latency, timeouts)
- Per-test handler overrides for isolated test scenarios
**When NOT to use:**
- Integration tests needing real backend validation (use a test database)
- Production builds (MSW should never ship to production)
- Pure function unit tests with no network calls
- Testing actual network failure modes (use test containers)
**Key patterns covered:**
- Handler/data separation for reusability and type safety
- Variant-based handlers (default, empty, error scenarios)
- Browser worker for development, server worker for tests
- Per-test handler overrides with `server.use()`
- Runtime variant switching for UI development
---
<philosophy>
Philosophy
MSW intercepts network requests at the service worker (browser) or class extension (Node) level, providing realistic API mocking without changing application code. Keep mock data separate from handlers for reusability, type handlers against your generated API types, and organize handlers by domain/feature.
</philosophy>
---
<patterns>
Core Patterns
Pattern 1: Separate Mock Data from Handlers
Define mock data as typed constants separate from MSW handlers. This enables type safety from your generated API types and reusability across handlers.
// mocks/features.ts
import type { GetFeaturesResponse } from "./api-types";
export const defaultFeatures: GetFeaturesResponse = {
features: [
{ id: "1", name: "Dark mode", status: "done" },
{ id: "2", name: "Auth", status: "in progress" },
],
};
export const emptyFeatures: GetFeaturesResponse = { features: [] };For full variant handler examples, see [examples/core.md](examples/core.md).
**When not to use:** When mock data is truly one-off and specific to a single test case (use inline data in the test instead).
---
Pattern 2: Handlers with Variant Switching
Create handlers that support multiple response scenarios (default, empty, error) with runtime switching for development and explicit overrides for testing.
import { http, HttpResponse } from "msw";
const API_ENDPOINT = "api/v1/features";
const HTTP_STATUS_OK = 200;
const HTTP_STATUS_INTERNAL_SERVER_ERROR = 500;
export const getFeaturesHandlers = {
defaultHandler: () =>
http.get(API_ENDPOINT, () =>
HttpResponse.json(defaultFeatures, { status: HTTP_STATUS_OK }),
),
emptyHandler: () =>
http.get(API_ENDPOINT, () =>
HttpResponse.json(emptyFeatures, { status: HTTP_STATUS_OK }),
),
errorHandler: () =>
http.get(
API_ENDPOINT,
() =>
new HttpResponse("Server error", {
status: HTTP_STATUS_INTERNAL_SERVER_ERROR,
}),
),
};For full implementation with runtime switching, see [examples/core.md](examples/core.md).
---
Pattern 3: Browser Worker (Development) vs Server Worker (Tests)
- Use `setupWorker` from `msw/browser` for browser/development
- Use `setupServer` from `msw/node` for Node/tests
- **Never swap them** -- `setupWorker` needs service worker APIs, `setupServer` needs Node APIs
// browser-worker.ts
import { setupWorker } from "msw/browser";
export const browserWorker = setupWorker(...handlers);
// server-worker.ts
import { setupServer } from "msw/node";
export const server = setupServer(...handlers);For browser app integration (SPA and SSR), see [examples/browser.md](examples/browser.md).
---
Pattern 4: Test Lifecycle
Always follow this lifecycle to prevent test pollution:
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Use `server.use()` for per-test overrides -- they are automatically cleaned up by `resetHandlers()`.
For per-test override examples, see [examples/core.md](examples/core.md).
</patterns>
---
<red_flags>
RED FLAGS
- ❌ Using `setupWorker` in Node tests or `setupServer` in browser -- wrong API for environment causes cryptic failures
- ❌ Not resetting handlers between tests (`afterEach(() => server.resetHandlers())`) -- causes test pollution
- ❌ Mixing handlers and mock data in same file -- reduces reusability and type safety
- ❌ Missing `await` when starting browser worker before render -- race conditions cause intermittent
Read more
name: web-mocks-msw description: MSW handlers, browser/server workers, test data. Use when setting up API mocking for development or testing, creating mock handlers with variants, or sharing mocks between browser and Node environments.
API Mocking with MSW
> **Quick Guide:** Handlers with variant switching (default, empty, error). Shared between browser (dev) and Node (tests). Separate mock data from handlers for reusability. Type-safe using your API's generated types. Use `setupWorker` (browser) and `setupServer` (Node) -- never swap them.
**Detailed Resources:**
- [examples/core.md](examples/core.md) - Mock data, variant handlers, server worker, per-test overrides, runtime switching, network simulation
- [examples/browser.md](examples/browser.md) - Browser worker setup, SPA/SSR integration
- [reference.md](reference.md) - Decision frameworks, red flags, anti-patterns
---
<critical_requirements>
CRITICAL: Before Using This Skill
**(You MUST separate mock data from handlers - handlers in `handlers/`, data in `mocks/`)**
**(You MUST use `setupWorker` for browser/development and `setupServer` for Node/tests - NEVER swap them)**
**(You MUST reset handlers after each test with `server.resetHandlers()` in `afterEach`)**
**(You MUST use named constants for HTTP status codes and delays - NO magic numbers)**
</critical_requirements>
---
**Auto-detection:** MSW, msw, mock handlers, mock data, API mocking, setupWorker, setupServer, http.get, HttpResponse
**When to use:**
- Mocking API responses during development before backend is ready
- Testing different API scenarios (success, empty, error states)
- Sharing the same mock definitions between browser dev and Node test environments
- Simulating network conditions (latency, timeouts)
- Per-test handler overrides for isolated test scenarios
**When NOT to use:**
- Integration tests needing real backend validation (use a test database)
- Production builds (MSW should never ship to production)
- Pure function unit tests with no network calls
- Testing actual network failure modes (use test containers)
**Key patterns covered:**
- Handler/data separation for reusability and type safety
- Variant-based handlers (default, empty, error scenarios)
- Browser worker for development, server worker for tests
- Per-test handler overrides with `server.use()`
- Runtime variant switching for UI development
---
<philosophy>
Philosophy
MSW intercepts network requests at the service worker (browser) or class extension (Node) level, providing realistic API mocking without changing application code. Keep mock data separate from handlers for reusability, type handlers against your generated API types, and organize handlers by domain/feature.
</philosophy>
---
<patterns>
Core Patterns
Pattern 1: Separate Mock Data from Handlers
Define mock data as typed constants separate from MSW handlers. This enables type safety from your generated API types and reusability across handlers.
// mocks/features.ts
import type { GetFeaturesResponse } from "./api-types";
export const defaultFeatures: GetFeaturesResponse = {
features: [
{ id: "1", name: "Dark mode", status: "done" },
{ id: "2", name: "Auth", status: "in progress" },
],
};
export const emptyFeatures: GetFeaturesResponse = { features: [] };For full variant handler examples, see [examples/core.md](examples/core.md).
**When not to use:** When mock data is truly one-off and specific to a single test case (use inline data in the test instead).
---
Pattern 2: Handlers with Variant Switching
Create handlers that support multiple response scenarios (default, empty, error) with runtime switching for development and explicit overrides for testing.
import { http, HttpResponse } from "msw";
const API_ENDPOINT = "api/v1/features";
const HTTP_STATUS_OK = 200;
const HTTP_STATUS_INTERNAL_SERVER_ERROR = 500;
export const getFeaturesHandlers = {
defaultHandler: () =>
http.get(API_ENDPOINT, () =>
HttpResponse.json(defaultFeatures, { status: HTTP_STATUS_OK }),
),
emptyHandler: () =>
http.get(API_ENDPOINT, () =>
HttpResponse.json(emptyFeatures, { status: HTTP_STATUS_OK }),
),
errorHandler: () =>
http.get(
API_ENDPOINT,
() =>
new HttpResponse("Server error", {
status: HTTP_STATUS_INTERNAL_SERVER_ERROR,
}),
),
};For full implementation with runtime switching, see [examples/core.md](examples/core.md).
---
Pattern 3: Browser Worker (Development) vs Server Worker (Tests)
- Use `setupWorker` from `msw/browser` for browser/development
- Use `setupServer` from `msw/node` for Node/tests
- **Never swap them** -- `setupWorker` needs service worker APIs, `setupServer` needs Node APIs
// browser-worker.ts
import { setupWorker } from "msw/browser";
export const browserWorker = setupWorker(...handlers);
// server-worker.ts
import { setupServer } from "msw/node";
export const server = setupServer(...handlers);For browser app integration (SPA and SSR), see [examples/browser.md](examples/browser.md).
---
Pattern 4: Test Lifecycle
Always follow this lifecycle to prevent test pollution:
beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close());
Use `server.use()` for per-test overrides -- they are automatically cleaned up by `resetHandlers()`.
For per-test override examples, see [examples/core.md](examples/core.md).
</patterns>
---
<red_flags>
RED FLAGS
- ❌ Using `setupWorker` in Node tests or `setupServer` in browser -- wrong API for environment causes cryptic failures
- ❌ Not resetting handlers between tests (`afterEach(() => server.resetHandlers())`) -- causes test pollution
- ❌ Mixing handlers and mock data in same file -- reduces reusability and type safety
- ❌ Missing `await` when starting browser worker before render -- race conditions cause intermittent
Showing the first part of this file.
The official skills marketplace for Agents Inc. 150+ skills covering everything from React and Prisma to Redis, ElevenLabs, and infrastructure tooling. Pick the skills that match your stack and install them via Claude Code. Need more control?
Repo: agents-inc/skills
Other skills on agents-inc-skills.
- /ai-infrastructure-huggingface-inference
Hugging Face Inference SDK patterns for TypeScript/Node.js — InferenceClient setup, chat completion, text generation, streaming, embeddings, image generation, audio transcription, translation, summarization, and Inference Endpoints
Open skill - /ai-infrastructure-litellm
LiteLLM proxy server setup, TypeScript client patterns via OpenAI SDK, model routing, fallbacks, load balancing, spend tracking, virtual keys, and production deployment
Open skill - /ai-infrastructure-modal
Serverless GPU compute platform for AI model deployment — web endpoints, GPU functions, model serving, and TypeScript client patterns
Open skill - /ai-infrastructure-ollama
Local LLM inference with the Ollama JavaScript client -- chat, streaming, tool calling, vision, embeddings, structured output, model management, and OpenAI-compatible endpoint
Open skill - /ai-infrastructure-replicate
Replicate SDK patterns for TypeScript/Node.js -- client setup, predictions, streaming, webhooks, file handling, model versioning, deployments, and training
Open skill - /ai-infrastructure-together-ai
Together AI SDK patterns for TypeScript — client setup, chat completions, streaming, structured output, function calling, embeddings, image generation, fine-tuning, and OpenAI-compatible endpoints
Open skill

