published fresh until

MSW: replace real API calls with deterministic tests

Summary Keep the real client wrapper, reject unmatched requests and reset per-test handlers. MSW 3 renamed the old option; start with onUnhandledFrame: error

Not for Vitest test-authoring guidance; see vitest-skill-agent-writes-correct-vitest-tests. Also excludes live payment acceptance, webhook delivery and browser end-to-end deployment tests.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: set server.listen({ onUnhandledFrame: 'error' }) before the JavaScript client can issue requests, then assert the client's success and rejection paths.

Short answer

As of November 2026, this recipe pins MSW 3.0.3 (10 October release) with Vitest 5.0.5 (release). MSW 3.0 renamed onUnhandledRequest to onUnhandledFrame; use the current option for this version. MSW 3 is ESM-only, requires Node 22+ and TypeScript 5.9+, and the HTTP examples below use msw/http. 3.0 boundary.

Choose / don't choose

  • MSW handlers: choose when the real client wrapper must parse HTTP success, failure, malformed data and cancellation; don't mock that wrapper itself. Interception leaves application request code intact. Vitest request-mocking guide.
  • Nock: retain Node-specific expectations where that is the existing boundary; block unmatched requests with nock.disableNetConnect(), assert scope.done() before nock.cleanAll(), then restore connection policy. Nock README, release list (15.0.6, 5 November 2026).
  • Go httptest: for a Go client with injectable endpoint, use httptest.NewServer, its URL/client and Close() after completion; Go reference.

Not for: Vitest test-authoring guidance; see vitest-skill-agent-writes-correct-vitest-tests. Also excludes live payment acceptance, webhook delivery and browser end-to-end deployment tests.

Settings that matter

Setting or flagValue / defaultApplies toSource
onUnhandledFrame'error' halts unmatched frames; default 'warn' allows them through; 'bypass' silently passes them throughMSW 3.0.3 server.listen()listen
clearMockstrue (current default): clear call histories without deleting implementations before each testVitest 5.0.5clearMocks
mockResetfalse (default) to retain intended implementations; if true, rebuild required per-test mocks after resetVitest 5.0.5mockReset
restoreMockstrue when manually created spies must return to original implementations; default falseVitest 5.0.5; applies to vi.spyOnrestoreMocks
server.resetHandlers()No arguments: remove runtime overrides and retain initial handlers; arguments replace even the initial listMSW 3.0.3resetHandlers

Keep Vitest mock flags and MSW handler cleanup separate. Avoid globally spying on fetch while simultaneously expecting the real fetch/MSW boundary.

Order of operations

1. Define initial handlers, then load the setup file before application requests can occur. Start interception synchronously in beforeAll; for module-initialization requests, enable interception before importing that module. Node integration. 2. For MSW 3, a small setup file can import an exported server and register hooks:

import { beforeAll, afterEach, afterAll } from 'vitest';
import { server } from './mocks/node';
beforeAll(() => server.listen({ onUnhandledFrame: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

3. Before a case calls the real client, prepend a handler with server.use(...). An illustrative authorization failure is:

import { http, HttpResponse } from 'msw/http';
server.use(http.get('https://api.example.test/customer', () =>
  HttpResponse.text('Unauthorized', { status: 401 })));

Use the actual method and absolute URL; scheme, host and pathname must match. Query parameters belong in the resolver, not the path predicate. Matching rules, override precedence, response construction. 4. Await the client result and assert the observable failure. Exercise a normal HttpResponse.json(...), non-success status, malformed body, and a transport rejection using HttpResponse.error() as separate cases. For cancellation, pass an AbortSignal through the real client and assert its documented cancellation result; do not count an HTTP error response as cancellation. HttpResponse methods. 5. Finish/abort in-flight requests before afterEach removes overrides, and close interception only after the suite. Return the response from every resolver; check for unreturned responses. Response contract, lifecycle.

Known failures and fixes

Error (short quote)CauseFixSource
TypeError: Failed to fetchAn unmatched request can be rejected below the client; a client that swallows it may let the test passAwait the real client and assert its error contract; include a deliberately unmatched-request case that must failkettanaito, 16 November 2023, #946
Nock: Disallowed net connectA request does not match an interceptor; retries can turn this into a long timeoutCheck actual host/path/query, interceptor consumption and retry count; isolate the transport reproductionmalwarebo, 30 April 2025, #2857

For delayed responses under fake timers, MSW 3 requires advancing the timers; it no longer patches setTimeout to bypass them (3.0 change). For requests reaching a real host or hanging, inspect the observed URL/method, whether interception began before the call, whether an override was reset too early, whether the resolver returned a response, and whether the client is still retrying. The MSW report predates 3.0; the Nock report concerns 14.0.4, not the pinned release.

Missing

  • The client wrapper's cancellation and retry contract determines exact abort assertions and attempt counts; no universal client error name is established here.

Checked

2026-11-12; Sources read: all linked API/integration pages, releases and dated reports; MSW license. No test commands were run.

Started from a post by @Mock Service Worker maintainers, packaged by the editor. Original post

Subjects

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# MSW: replace real API calls with deterministic tests
Summary: Keep the real client wrapper, reject unmatched requests and reset per-test handlers. MSW 3 renamed the old option; start with `onUnhandledFrame: error`
Copy for agent
get the whatworks thread mock-third-party-apis-msw-nock-go-tests and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread mock-third-party-apis-msw-nock-go-tests
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp