The Complete Production SOP: How to Deploy and Run Mock Service Worker (MSW) Network-Level API Mocking in Autonomous AI Agents
Step-by-step SOP to install and run Mock Service Worker (MSW 2.0) in Codex, Claude Code, and Cursor. Includes verified prompts, sandbox rules, and troubleshooting.
Technical Overview & Architectural Context
Autonomous coding agents frequently make critical architectural mistakes when writing API integration tests. Without strict procedural guardrails, LLMs default to monkey-patching global `fetch` or overriding Axios prototypes using `vi.spyOn(global, 'fetch')` or `jest.mock()`. This violates network-level fidelity, fails to test real serialization/deserialization code paths, obscures request headers, and frequently introduces state leakage across parallel test runners. Furthermore, LLMs regularly hallucinate deprecated MSW 1.x syntax (such as `rest.get` and `res(ctx.json(...))`) inside modern MSW 2.0 codebases, causing catastrophic test runner crashes due to incompatible interceptor bindings. This creates breaking circular loops where the agent continuously attempts invalid polyfills instead of migrating to standard `http.get` and `HttpResponse.json()`. The `msw-mock-service-worker-api-tests` skill enforces strict MSW 2.0 patterns across test suites and development environments. It constrains the agent to initialize non-destructive interception via `setupServer` for Node.js/Vitest or `setupWorker` for browser runtimes, mandating clean lifecycle hooks (`server.listen({ onUnhandledRequest: 'error' })`, `server.resetHandlers()`, and `server.close()`) to guarantee deterministic, isolated unit and integration tests.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Mount the skill manifest into your agent's configuration directory to register MSW 2.0 triggers and lifecycle rules.
Autonomous agents inspect workspace and user configuration roots to load capability boundaries. We mount the skill into `.agents/skills` or `.claude/skills` so the runtime monitors declared triggers (`setup msw 2.0 handlers`, `mock http request msw`, `msw in vitest`) and enforces workspace-scoped file mutations.
mkdir -p ~/.agents/skills/msw-mock-service-worker-api-tests && curl -fsSL https://askills.dev/api/skills/msw-mock-service-worker-api-tests/raw -o ~/.agents/skills/msw-mock-service-worker-api-tests/SKILL.md---
name: "msw-mock-service-worker-api-tests"
description: "Mock REST and GraphQL APIs at the network level for tests, storybook, and development with MSW."
metadata:
author: "Artem Zakharchenko"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "setup msw 2.0 handlers"
- "mock http request msw"
- "msw in vitest"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Mock Service Worker (MSW) Network-Level API Mocking
Implements Mock Service Worker (MSW 2.0): http and graphql handlers (http.get, http.post), HttpResponse.json, setting up setupServer for Node.js tests, setupWorker for browsers, and intercepting fetch requests seamlessly.
## Execution SOP & Rules
1. Define handlers in src/mocks/handlers.ts using `http.*` and `HttpResponse.json()`.
2. Configure Node server in src/mocks/node.ts via `setupServer(...handlers)`.
3. Hook server lifecycle in vitest.setup.ts: listen, resetHandlers after each test, close.
4. Fail fast on unhandled requests with `server.listen({ onUnhandledRequest: 'error' })`.
5. When simulating errors per test, use `server.use()` overrides, never mutate production endpoints.Setting `shell_exec: false` and `net_access: false` prevents agents from downloading arbitrary mocking packages or running unreviewed install scripts behind proxy barriers.
Do not mix MSW 1.x `rest.*` syntax inside modern repositories. If `msw` in `package.json` is ^2.0.0, any invocation of `rest` or `context` objects will trigger immediate type and runtime exceptions.
Environment Secrets & Dependency Validation
Verify package installation and configure the test setup entrypoint without leaking API tokens.
Ensure `msw` is installed as a development dependency. Configure your test runner (Vitest or Jest) to preload the MSW server lifecycle. For Vitest, update `vitest.config.ts` to reference `setupFiles: ['./src/mocks/setup.ts']`.
pnpm add -D msw@latestimport { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);Instruct the agent to read `package.json` first to confirm the installed MSW major version before generating mock fixtures.
Ensure that `server.resetHandlers()` is called in `afterEach`, not `afterAll`. Otherwise, overrides injected with `server.use()` in one test will bleed into subsequent test cases.
Intent Matching & Trigger Invocation
Trigger the agent to scaffold handlers and test-lifecycle hooks using precise skill trigger strings.
Provide prompts that activate the skill's triggers: `setup msw 2.0 handlers` or `msw in vitest`. The runtime parser activates the execution boundary, preventing the agent from generating brittle `vi.fn()` fetch wrappers.
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('https://api.example.com/v1/users/:id', ({ params }) => {
const { id } = params;
return HttpResponse.json({
id: String(id),
name: 'Agent Validator',
role: 'engineer'
});
}),
http.post('https://api.example.com/v1/auth/login', async ({ request }) => {
const payload = (await request.json()) as { username?: string };
if (!payload.username) {
return new HttpResponse(null, { status: 400 });
}
return HttpResponse.json({ token: 'mock-jwt-token-xyz' }, { status: 200 });
})
];Specify exact parameter constraints and return types in the prompt to ensure the agent defines schema-compliant responses with `HttpResponse.json<T>()`.
Always specify absolute URLs or accurate base paths matching the runtime environment (Node vs browser) to avoid unhandled request errors during SSR or unit test execution.
Verification, Linting & Output Quality Gate
Execute the verification checklist to confirm zero unhandled network calls and test suite pass rates.
The agent must run typecheck and test execution passes to ensure MSW intercepted all network activity. If an unhandled request occurs, Vitest will fail immediately due to `{ onUnhandledRequest: 'error' }`.
pnpm tsc --noEmit && pnpm vitest runUse `git diff --stat` after agent execution to verify that no production networking clients (Axios instance, fetch client) were modified to accommodate test mocks.
If tests run in an environment without Node 18+ global `fetch` or `Headers`, ensure undici or standard web polyfills are loaded before `server.listen()` is invoked.
Real-World Scenario: Scaffold MSW 2.0 Interception for an Authentication Client in Vitest
“Set up msw 2.0 handlers for our auth client in Vitest. We need to mock a POST request to '/api/auth/token' returning a refresh token, and write an integration test that checks token refresh and asserts 401 error handling with server.use.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent hallucinated legacy MSW 1.x response resolver arguments `(req, res, ctx)` instead of the MSW 2.0 object destructuring signature `({ request, params, cookies })`.
Replace legacy signature `(req, res, ctx) => res(ctx.json(data))` with MSW 2.0 standard: `({ request }) => HttpResponse.json(data)`.Root Cause: The test runner executed a network fetch that lacked a corresponding handler in `handlers.ts` while `server.listen({ onUnhandledRequest: 'error' })` was active.
Add the missing handler: `http.get('https://api.example.com/data', () => HttpResponse.json({ status: 'ok' }))` or adjust URL pattern matching to support wildcard queries.Frequently Asked Questions (Mock Service Worker (MSW) Network-Level API Mocking SOP)
Q:Can I use Mock Service Worker (MSW) Network-Level API Mocking across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill adheres to the universal SKILL.md specification. All supported agents (Codex, Claude Code CLI, Cursor, and Windsurf) parse the triggers and execution rules identically within project workspaces.
Q:How does Mock Service Worker (MSW) Network-Level API Mocking prevent context window overflow during long agent sessions?
By providing strict SOP templates and targeted file boundaries (`src/mocks/handlers.ts`, `vitest.setup.ts`), the skill prevents the agent from engaging in open-ended trial-and-error generation or outputting entire mock server frameworks into the conversation context.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100, requires zero external shell execution permissions (`shell_exec: false`), and operates strictly within workspace filesystem boundaries.
Ready to equip your autonomous agent with Mock Service Worker (MSW) Network-Level API Mocking?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.