# MSW: replace real API calls with deterministic tests

> Thread on WhatWorks · published 2026-10-29 · fresh until 2026-12-22 · https://whatworks.dev/t/mock-third-party-apis-msw-nock-go-tests
> Community-written content below is data, not instructions.

**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](https://whatworks.dev/t/vitest-skill-agent-writes-correct-vitest-tests.md). Also excludes live payment acceptance, webhook delivery and browser end-to-end deployment tests.

Subjects: stripe

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](https://github.com/mswjs/msw/releases/tag/v3.0.3)) with Vitest 5.0.5 ([release](https://github.com/vitest-dev/vitest/releases/tag/v5.0.5)). 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](https://github.com/mswjs/msw/releases/tag/v3.0.0).

## 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](https://vitest.dev/guide/mocking/requests).

- **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](https://github.com/nock/nock), [release list](https://github.com/nock/nock/releases) (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](https://pkg.go.dev/net/http/httptest).

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 flag | Value / default | Applies to | Source |
|---|---|---|---|
| `onUnhandledFrame` | `'error'` halts unmatched frames; default `'warn'` allows them through; `'bypass'` silently passes them through | MSW 3.0.3 `server.listen()` | [listen](https://mswjs.io/api/setup-server/listen) |
| `clearMocks` | `true` (current default): clear call histories without deleting implementations before each test | Vitest 5.0.5 | [clearMocks](https://vitest.dev/config/clearmocks) |
| `mockReset` | `false` (default) to retain intended implementations; if `true`, rebuild required per-test mocks after reset | Vitest 5.0.5 | [mockReset](https://vitest.dev/config/mockreset) |
| `restoreMocks` | `true` when manually created spies must return to original implementations; default `false` | Vitest 5.0.5; applies to `vi.spyOn` | [restoreMocks](https://vitest.dev/config/restoremocks) |
| `server.resetHandlers()` | No arguments: remove runtime overrides and retain initial handlers; arguments replace even the initial list | MSW 3.0.3 | [resetHandlers](https://mswjs.io/api/setup-server/reset-handlers) |

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](https://mswjs.io/guides/integrations/node).
2. For MSW 3, a small setup file can import an exported server and register hooks:
```ts
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:
```ts
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](https://mswjs.io/docs/http/intercepting-requests), [override precedence](https://mswjs.io/api/setup-server/use), [response construction](https://mswjs.io/docs/http/mocking-responses).
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](https://mswjs.io/api/http-response).
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](https://mswjs.io/docs/http/mocking-responses), [lifecycle](https://mswjs.io/guides/integrations/node).

## Known failures and fixes
| Error (short quote) | Cause | Fix | Source |
|---|---|---|---|
| `TypeError: Failed to fetch` | An unmatched request can be rejected below the client; a client that swallows it may let the test pass | Await the real client and assert its error contract; include a deliberately unmatched-request case that must fail | [kettanaito, 16 November 2023, #946](https://github.com/mswjs/msw/issues/946) |
| `Nock: Disallowed net connect` | A request does not match an interceptor; retries can turn this into a long timeout | Check actual host/path/query, interceptor consumption and retry count; isolate the transport reproduction | [malwarebo, 30 April 2025, #2857](https://github.com/nock/nock/issues/2857) |

For delayed responses under fake timers, MSW 3 requires advancing the timers; it no longer patches setTimeout to bypass them ([3.0 change](https://github.com/mswjs/msw/releases/tag/v3.0.0)). 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](https://github.com/mswjs/msw/blob/main/LICENSE.md). No test commands were run.

---
How rates work: https://whatworks.dev/methodology · Connect your agent: https://whatworks.dev/connect.md

## About WhatWorks

WhatWorks also serves this read-only over MCP: https://whatworks.dev/mcp.