msw-handlers
БесплатноБез исполняемых скриптовНе проверенUse when JavaScript or TypeScript tests need to mock fetch or XHR calls to an HTTP API, such as replacing hand-rolled fetch mocks or testing loading and error…
от testland★ 18 звёзд на GitHubОб этом скилле
msw-handlers
Overview
Mock Service Worker (MSW) intercepts HTTP requests at the network
layer using Service Workers in the browser and a request-
interception adapter in Node.js (msw-getting-started). The
same handler set works for both - the test author writes one
http.get mock and uses it from Vitest unit tests AND from a
Cypress browser test.
When to use
- The project is JavaScript / TypeScript.
- Tests need to mock HTTP at the same layer as the SUT -
intercepting actual
fetch/XHRcalls rather than stubbing the HTTP client library. - Both browser tests (Cypress / Playwright) and Node tests (Vitest / Jest) need the same mock data - MSW's cross-environment consistency is its key advantage.
- The team wants per-test handler overrides (
server.use(...)) layered on top of project-wide defaults.
If the project is JVM, use wiremock-stubs.
For multi-protocol mocking (TCP / SMTP / LDAP / gRPC), see the
Mountebank reference in wiremock-stubs.
Install
npm i msw --save-dev
(Per msw-getting-started.)
For browser setup, also generate the worker script:
npx msw init public/ --save
This places mockServiceWorker.js in your public directory; the
worker script is what the browser registers to intercept requests.
Authoring handlers
Per msw-getting-started:
// src/mocks/handlers.js
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('https://api.example.com/user', () => {
return HttpResponse.json({ id: 'abc-123', firstName: 'John' });
}),
http.post('https://api.example.com/orders', async ({ request }) => {
const body = await request.json();
return HttpResponse.json({ order_id: 42, ...body }, { status: 201 });
}),
http.get('https://api.example.com/orders/:id', ({ params }) => {
return HttpResponse.json({ order_id: Number(params.id), status: 'shipped' });
}),
];
Handler signature: http.<verb>(url, resolver). The resolver
receives { request, params, cookies } and returns an
HttpResponse.
HttpResponse static helpers
| Helper | Effect |
|---|---|
HttpResponse.json(body, init?) |
JSON response with Content-Type: application/json. |
HttpResponse.text(body, init?) |
Plain text response. |
HttpResponse.error() |
Network-level error (e.g. simulate offline). |
new HttpResponse(...) |
Full-control raw response. |
The init object accepts status, statusText, headers -
matching the standard Response API.
Pattern matching
| Pattern | Notes |
|---|---|
'https://api.example.com/orders/:id' |
Path param exposed via params.id. |
'/api/orders' |
Same-origin path; matches relative to current host. |
'*\\/orders' |
Wildcards via standard URL pattern. |
/^\\/api\\/orders\\/[0-9]+$/ |
Regex match. |
Browser setup - setupWorker
// src/mocks/browser.js
import { setupWorker } from 'msw/browser';
import { handlers } from './handlers';
export const worker = setupWorker(...handlers);
// Start the worker only in development / test
if (process.env.NODE_ENV !== 'production') {
worker.start();
}
(Per msw-getting-started.)
In a Storybook + MSW combo, kick off worker.start() from the
preview file. For Cypress: register the worker before any test
that depends on the mocks.
Node setup - setupServer
// src/mocks/node.js
import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);
// vitest.setup.js (or jest.setup.js)
import { server } from './src/mocks/node';
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
(Per msw-getting-started.)
| Hook | When | Purpose |
|---|---|---|
server.listen() |
beforeAll |
Activate mocking. |
server.resetHandlers() |
afterEach |
Clear per-test overrides. |
server.close() |
afterAll |
Tear down; release resources. |
server.use(...) |
Per-test | Add / |
Установить msw-handlers в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл msw-handlers?
Use when JavaScript or TypeScript tests need to mock fetch or XHR calls to an HTTP API, such as replacing hand-rolled fetch mocks or testing loading and error responses, in Vitest or Jest and in Cypress or Playwright: writes Mock Service Worker handlers (`http.get`, `http.post`, `HttpResponse.json`), wires `setupServer` (Node) or `setupWorker` (browser), and manages the `listen` / `resetHandlers` / `close` lifecycle.
Как установить скилл msw-handlers?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл msw-handlers запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic