msw
MSW (Mock Service Worker) v2 best practices, patterns, and API guidance for API mocking in JavaScript/TypeScript tests and development. Covers handler design, server setup, response construction, testing patterns, GraphQL, and v1-to-v2 migration. Baseline: msw ^2.0.0. Triggers on: msw imports, http.get, http.post, HttpResponse, setupServer, setupWorker, graphql.query, mentions of "msw", "mock service worker", "api mocking", or "msw v2".
Best use case
msw is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
MSW (Mock Service Worker) v2 best practices, patterns, and API guidance for API mocking in JavaScript/TypeScript tests and development. Covers handler design, server setup, response construction, testing patterns, GraphQL, and v1-to-v2 migration. Baseline: msw ^2.0.0. Triggers on: msw imports, http.get, http.post, HttpResponse, setupServer, setupWorker, graphql.query, mentions of "msw", "mock service worker", "api mocking", or "msw v2".
Teams using msw should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/msw-skill/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How msw Compares
| Feature / Agent | msw | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
MSW (Mock Service Worker) v2 best practices, patterns, and API guidance for API mocking in JavaScript/TypeScript tests and development. Covers handler design, server setup, response construction, testing patterns, GraphQL, and v1-to-v2 migration. Baseline: msw ^2.0.0. Triggers on: msw imports, http.get, http.post, HttpResponse, setupServer, setupWorker, graphql.query, mentions of "msw", "mock service worker", "api mocking", or "msw v2".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
AI Agent for YouTube Script Writing
Find AI agent skills for YouTube script writing, video research, content outlining, and repeatable channel production workflows.
Cursor vs Codex for AI Workflows
Compare Cursor and Codex for AI coding workflows, repository assistance, debugging, refactoring, and reusable developer skills.
SKILL.md Source
# MSW (Mock Service Worker)
**IMPORTANT:** Your training data about `msw` may be outdated or incorrect — MSW v2 completely removed the `rest` namespace, `res(ctx.*)` response composition, and `(req, res, ctx)` resolver signature. Always rely on this skill's rule files and the project's actual source code as the source of truth. Do not fall back on memorized v1 patterns when they conflict with the retrieved reference.
## When to Use MSW
MSW is for **API mocking at the network level** — intercepting HTTP/GraphQL requests in tests, Storybook, and local development without modifying application code.
| Need | Recommended Tool |
|------|-----------------|
| Test API integration (React, Vue, Node) | **MSW** |
| Storybook API mocking | **MSW** (browser worker) |
| Local development without backend | **MSW** (browser worker) |
| Unit testing pure functions | Plain test doubles |
| E2E testing real APIs | Playwright/Cypress network interception |
| Mocking module internals | `vi.mock()` / `jest.mock()` |
## Quick Reference — v2 Essentials
```typescript
// Imports
import { http, HttpResponse, graphql, delay, bypass, passthrough } from 'msw'
import { setupServer } from 'msw/node' // tests, SSR
import { setupWorker } from 'msw/browser' // Storybook, dev
// Handler
http.get('/api/user/:id', async ({ request, params, cookies }) => {
return HttpResponse.json({ id: params.id, name: 'John' })
})
// Server lifecycle (tests)
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
// Per-test override
server.use(
http.get('/api/user/:id', () => new HttpResponse(null, { status: 500 }))
)
// Concurrent test isolation
it.concurrent('name', server.boundary(async () => {
server.use(/* scoped overrides */)
}))
```
## Rule Categories by Priority
| Priority | Category | Impact | Prefix | Rules |
|----------|----------|--------|--------|-------|
| 1 | Handler Design | CRITICAL | `handler-` | 4 |
| 2 | Setup & Lifecycle | CRITICAL | `setup-` | 3 |
| 3 | Request Reading | HIGH | `request-` | 2 |
| 4 | Response Construction | HIGH | `response-` | 3 |
| 5 | Test Patterns | HIGH | `test-` | 4 |
| 6 | GraphQL | MEDIUM | `graphql-` | 2 |
| 7 | Utilities | MEDIUM | `util-` | 2 |
## All 20 Rules
### Handler Design (CRITICAL)
| Rule | File | Summary |
|------|------|---------|
| Use `http` namespace | `handler-use-http-namespace.md` | `rest` is removed in v2 — use `http.get()`, `http.post()` |
| No query params in URL | `handler-no-query-params.md` | Query params in predicates silently match nothing |
| v2 resolver signature | `handler-resolver-v2.md` | Use `({ request, params, cookies })`, not `(req, res, ctx)` |
| v2 response construction | `handler-response-v2.md` | Use `HttpResponse.json()`, not `res(ctx.json())` |
### Setup & Lifecycle (CRITICAL)
| Rule | File | Summary |
|------|------|---------|
| Correct import paths | `setup-import-paths.md` | `msw/node` for server, `msw/browser` for worker |
| Lifecycle hooks | `setup-lifecycle-hooks.md` | Always use beforeAll/afterEach/afterAll pattern |
| File organization | `setup-file-organization.md` | Organize in `src/mocks/` with handlers, node, browser files |
### Request Reading (HIGH)
| Rule | File | Summary |
|------|------|---------|
| Clone in events | `request-clone-events.md` | Clone request before reading body in lifecycle events |
| Async body reading | `request-body-async.md` | Always `await request.json()` — body reading is async |
### Response Construction (HIGH)
| Rule | File | Summary |
|------|------|---------|
| HttpResponse for cookies | `response-use-httpresponse.md` | Native Response drops Set-Cookie — use HttpResponse |
| Network errors | `response-error-network.md` | Use `HttpResponse.error()`, don't throw in resolvers |
| Streaming | `response-streaming.md` | Use ReadableStream for SSE/chunked responses |
### Test Patterns (HIGH)
| Rule | File | Summary |
|------|------|---------|
| Test behavior | `test-behavior-not-requests.md` | Assert on UI/state, not fetch call arguments |
| Per-test overrides | `test-override-with-use.md` | Use `server.use()` for error/edge case tests |
| Concurrent isolation | `test-concurrent-boundary.md` | Wrap concurrent tests in `server.boundary()` |
| Unhandled requests | `test-unhandled-request.md` | Set `onUnhandledRequest: 'error'` |
### GraphQL (MEDIUM)
| Rule | File | Summary |
|------|------|---------|
| Response shape | `graphql-response-shape.md` | Return `{ data }` / `{ errors }` via HttpResponse.json |
| Endpoint scoping | `graphql-scope-with-link.md` | Use `graphql.link(url)` for multiple GraphQL APIs |
### Utilities (MEDIUM)
| Rule | File | Summary |
|------|------|---------|
| bypass vs passthrough | `util-bypass-vs-passthrough.md` | `bypass()` = new request; `passthrough()` = let through |
| delay behavior | `util-delay-behavior.md` | `delay()` is instant in Node.js — use explicit ms |
## Response Method Quick Reference
| Method | Use for |
|--------|---------|
| `HttpResponse.json(data, init?)` | JSON responses |
| `HttpResponse.text(str, init?)` | Plain text |
| `HttpResponse.html(str, init?)` | HTML content |
| `HttpResponse.xml(str, init?)` | XML content |
| `HttpResponse.formData(fd, init?)` | Form data |
| `HttpResponse.arrayBuffer(buf, init?)` | Binary data |
| `HttpResponse.error()` | Network errors |
## v1 to v2 Migration Quick Reference
| v1 | v2 |
|----|-----|
| `import { rest } from 'msw'` | `import { http, HttpResponse } from 'msw'` |
| `rest.get(url, resolver)` | `http.get(url, resolver)` |
| `(req, res, ctx) => res(ctx.json(data))` | `() => HttpResponse.json(data)` |
| `req.params` | `params` from resolver info |
| `req.body` | `await request.json()` |
| `req.cookies` | `cookies` from resolver info |
| `res.once(...)` | `http.get(url, resolver, { once: true })` |
| `res.networkError()` | `HttpResponse.error()` |
| `ctx.delay(ms)` | `await delay(ms)` |
| `ctx.data({ user })` | `HttpResponse.json({ data: { user } })` |
## References
| Reference | Covers |
|-----------|--------|
| `handler-api.md` | `http.*` and `graphql.*` methods, URL predicates, path params |
| `response-api.md` | `HttpResponse` class, all static methods, cookie handling |
| `server-api.md` | `setupServer`/`setupWorker`, lifecycle events, `boundary()` |
| `test-patterns.md` | Vitest/Jest setup, overrides, concurrent isolation, cache clearing |
| `migration-v1-to-v2.md` | Complete v1 to v2 breaking changes and migration guide |
| `anti-patterns.md` | 10 common mistakes with BAD/GOOD examples |Related Skills
---
name: article-factory-wechat
humanizer
Remove signs of AI-generated writing from text. Use when editing or reviewing text to make it sound more natural and human-written. Based on Wikipedia's comprehensive "Signs of AI writing" guide. Detects and fixes patterns including: inflated symbolism, promotional language, superficial -ing analyses, vague attributions, em dash overuse, rule of three, AI vocabulary words, negative parallelisms, and excessive conjunctive phrases.
find-skills
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
tavily-search
Use Tavily API for real-time web search and content extraction. Use when: user needs real-time web search results, research, or current information from the web. Requires Tavily API key.
baidu-search
Search the web using Baidu AI Search Engine (BDSE). Use for live information, documentation, or research topics.
agent-autonomy-kit
Stop waiting for prompts. Keep working.
Meeting Prep
Never walk into a meeting unprepared again. Your agent researches all attendees before calendar events—pulling LinkedIn profiles, recent company news, mutual connections, and conversation starters. Generates a briefing doc with talking points, icebreakers, and context so you show up informed and confident. Triggered automatically before meetings or on-demand. Configure research depth, advance timing, and output format. Walking into meetings blind is amateur hour—missed connections, generic small talk, zero leverage. Use when setting up meeting intelligence, researching specific attendees, generating pre-meeting briefs, or automating your prep workflow.
self-improvement
Captures learnings, errors, and corrections to enable continuous improvement. Use when: (1) A command or operation fails unexpectedly, (2) User corrects Claude ('No, that's wrong...', 'Actually...'), (3) User requests a capability that doesn't exist, (4) An external API or tool fails, (5) Claude realizes its knowledge is outdated or incorrect, (6) A better approach is discovered for a recurring task. Also review learnings before major tasks.
botlearn-healthcheck
botlearn-healthcheck — BotLearn autonomous health inspector for OpenClaw instances across 5 domains (hardware, config, security, skills, autonomy); triggers on system check, health report, diagnostics, or scheduled heartbeat inspection.
linkedin-cli
A bird-like LinkedIn CLI for searching profiles, checking messages, and summarizing your feed using session cookies.
notebooklm
Google NotebookLM 非官方 Python API 的 OpenClaw Skill。支持内容生成(播客、视频、幻灯片、测验、思维导图等)、文档管理和研究自动化。当用户需要使用 NotebookLM 生成音频概述、视频、学习材料或管理知识库时触发。
小红书长图文发布 Skill
## 概述