How-to › Test and mock integrations

How to intercept fetch calls in browser tests with MSW#

Share MSW handlers between Chromium and Node tests, assert what a component renders for a 500, and fail unhandled requests with the MSW 3 option onUnhandledFrame.

Audience
API consumer
Level
intermediate
Topic
Mock an API
Languages
TypeScript and JavaScript
Verified

Your component test checks the error alert, and it passes only on the days the staging API is down. The real service cannot be made to answer 500 on demand. A request you forgot to stub goes out to the network with a console warning, so the suite fails whenever that network does.

What you get

You will end up with one file of MSW handlers that a Chromium run and a Node suite both use. A test asserts the alert a 500 renders, and the setup fails any request no handler covers. This is for you if your components call fetch themselves.

Short answer

Write MSW request handlers once, start them with setupWorker in the browser and setupServer in Node, and override one per test with use() to return a 500. The component’s own fetch code runs against them with no server. In MSW 3, pass onUnhandledFrame: 'error', because MSW 3 ignores the MSW 2 name onUnhandledRequest, keeps its default of a warning, and lets unmatched requests reach the network.

You will need

Node 22.12 or later, because msw 3.0.8 declares >=22.12.0 in its engines field. A browser runner for the browser half: the sample drives Chromium through Playwright. TypeScript is optional and catches the renamed option. Verified 2026-11-30 against Node 22.23.5, msw 3.0.8, TypeScript 5.9.3, Playwright 1.63.0 and Chromium 158.0.8127.36.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Cypress cy.interceptThe suite already runs in Cypress and one spec needs one stubStubs live inside Cypress specs, so Node unit tests cannot reuse themUnit tests and browser tests need the same responses
MSWUnit, component and end to end tests should share one set of responsesA dependency, a worker script served from your origin, and an option renamed between majorsOne spec needs one stub inside a runner that already intercepts
Playwright page.routeThe suite already runs in Playwright and a stub serves one specRoutes exist only in Playwright, and unmatched requests reach the network without a catch-allThe same handlers must serve a Node suite too

MSW intercepts inside the page through a service worker, so the component’s own fetch runs and the handlers move to Node unchanged. Its price is setup: a worker file on your origin and a start-up call before the first request. page.route and cy.intercept need neither, and a one-off stub is a single call. Their stubs belong to one runner, so a node --test or Vitest suite cannot load them.

Write the handlers once

A handler pairs a method and a URL pattern with a response. The * origin matches the page’s own origin in a browser and any base URL a Node test passes.

import { http, HttpResponse } from 'msw'

// One set of handlers for every runner. The wildcard origin matches the page's
// own origin in a browser and any base URL a Node test passes.
export const handlers = [
  http.get('*/api/user', () => HttpResponse.json({ name: 'Ada Lovelace', plan: 'Team' })),
]

// Per-test overrides, applied with worker.use() or server.use().
export const userFails = http.get('*/api/user', () =>
  HttpResponse.json({ error: 'upstream unavailable' }, { status: 500 }),
)

The component, profile.js, fetches api/user relative to a base URL and returns an alert for any status that is not 2xx. It knows nothing about MSW, which is the point: the code under test is the code that ships.

Start the worker in the page

In the browser, setupWorker registers mockServiceWorker.js, which answers the page’s requests from the handlers. The MSW documentation has you copy that file into your public directory with npx msw init, so it is served from your origin.1

import { setupWorker } from 'msw/browser'
import { handlers, userFails } from '../handlers.js'
import { mountProfile } from '../profile.js'

const worker = setupWorker(...handlers)
await worker.start({
  serviceWorker: { url: '/mockServiceWorker.js' },
  onUnhandledFrame: 'error',
  quiet: true,
})

const root = /** @type {HTMLElement} */ (document.querySelector('#profile'))
const base = `${location.origin}/`
const results = {}
results.shared = await mountProfile(root, base)
worker.use(userFails)
results.fails = await mountProfile(root, base)

worker.use(userFails) puts the 500 in front of the shared handler, and worker.resetHandlers() takes it away again. The sample has no bundler, so browser/index.html loads MSW’s IIFE build and an import map points msw at it. With Vite or Vitest browser mode, that shim goes away.

The gate that checks this page has no browser, so record.sh runs the page once in Chromium. Its static server has no /api/ routes and counts every request that reaches one.

cat records/browser-run.txt
Chromium 158.0.8127.36, Playwright 1.63.0, msw 3.0.8
MSW setupWorker with the shared handlers
  shared handler, text shown: "Ada LovelaceTeam plan"
  then worker.use(userFails):
  /api/user, text shown:      "Profile unavailable: HTTP 500"
  markup on the page at exit: <p role="alert">Profile unavailable: HTTP 500</p>
  unhandled GET /api/billing: answered 500, body.message: [MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledFrame" option.
  console: [MSW] Error: intercepted a request without a matching request handler:
  requests that reached the static server: none

The page rendered both states without a single request reaching the server.

Run the same handlers in Node

setupServer takes the same handler array and intercepts fetch, http and XMLHttpRequest calls in the process.2 The setup file sets the unhandled-request strategy, and its self-check refuses to run the suite when MSW cannot see the requests at all.

import { setupServer } from 'msw/node'
import { http, HttpResponse } from 'msw'
import { handlers } from './handlers.js'

export const server = setupServer(...handlers)

// MSW 3 reads onUnhandledFrame. MSW 2 called it onUnhandledRequest, and MSW 3
// ignores that name without a word, falling back to "warn".
// The self-check sends one request to the API's own host and refuses to go on
// unless MSW answered it, which it does not when Node sends fetch to a proxy.
/** @param {string | URL} apiBase */
export async function startMocking(apiBase) {
  server.listen({ onUnhandledFrame: 'error' })
  const probe = new URL('/__msw-self-check', apiBase)
  const token = crypto.randomUUID()
  server.use(http.get(probe.href, () => HttpResponse.text(token)))
  const answer = await fetch(probe, { signal: AbortSignal.timeout(5_000) }).then(
    (res) => res.text(),
    () => null,
  )
  server.resetHandlers()
  if (answer !== token) {
    server.close()
    throw new Error(
      `MSW did not answer a request to ${probe.origin}. If NODE_USE_ENV_PROXY or ` +
        '--use-env-proxy is on, add that host to NO_PROXY for the test run.',
    )
  }
}

The tests point the component at http://api.example.test/v1/, a host with no server behind it. Each override is reset after its test, so one test’s 500 never leaks into the next.

test.before(() => startMocking(API))
test.afterEach(() => server.resetHandlers())
test.after(() => server.close())

test('renders the user from the shared handler', async () => {
  assert.equal(await profileView(API), '<h2>Ada Lovelace</h2><p>Team plan</p>')
})

test('renders an alert when the API answers 500', async () => {
  server.use(userFails)
  assert.equal(await profileView(API), '<p role="alert">Profile unavailable: HTTP 500</p>')
})

Keep a proxy from bypassing the handlers

A suite that passed locally fails on a runner that sets NODE_USE_ENV_PROXY=1. Node 22 then tunnels requests over the proxy that HTTP_PROXY or HTTPS_PROXY names, as the NODE_USE_ENV_PROXY reference describes. proxy.mjs requests a URL the shared handler covers, with a stand-in proxy on 127.0.0.1 that counts what reaches it.

node proxy.mjs
GET http://api.example.test/v1/api/user, a URL the shared handler covers
no proxy settings
  MSW printed: nothing
  request:     answered 200 {"name":"Ada Lovelace","plan":"Team"}
  reached the stand-in proxy: 0
NODE_USE_ENV_PROXY=1 and HTTP_PROXY
  MSW printed: nothing
  request:     rejected by fetch
  reached the stand-in proxy: 1
the same, plus NO_PROXY=api.example.test
  MSW printed: nothing
  request:     answered 200 {"name":"Ada Lovelace","plan":"Team"}
  reached the stand-in proxy: 0
NODE_USE_ENV_PROXY=1 and HTTP_PROXY, through startMocking()
  MSW printed: nothing
  request:     rejected: MSW did not answer a request to http://api.example.test. If NODE_USE_ENV_PROXY or --use-env-proxy is on, add that host to NO_PROXY for the test run.
  reached the stand-in proxy: 1

With the proxy on, msw 3.0.8 neither answered from its handler nor reported the request as unhandled, so onUnhandledFrame: 'error' never fired. The call went to the proxy, which is the network path the strategy exists to close. Listing the API host in NO_PROXY restores interception, and the self-check in startMocking turns the silent case into a failed start.

Check it worked

Run the Node suite:

node --test profile.test.mjs
1..8
# tests 8
# suites 0
# pass 8
# fail 0
# cancelled 0
# skipped 0
# todo 0

Eight tests pass. The 500 test expects the literal <p role="alert">Profile unavailable: HTTP 500</p>, the same markup the Chromium record shows. The last test reads records/browser-run.txt and fails if the committed browser run stops showing both renders or shows a request reaching the server.

When it goes wrong

The suite passes at your desk and fails on a CI runner with no outbound access. A request no handler covers went to the network. unhandled.mjs sends one such request to a stand-in API on 127.0.0.1 under each listen() option and counts what arrives.

node unhandled.mjs
no MSW at all (control)
  MSW printed: nothing
  request:     answered 200 {"source":"network"}
  reached the stand-in API: 1
listen()
  MSW printed: warning
  request:     answered 200 {"source":"network"}
  reached the stand-in API: 1
listen({ onUnhandledRequest: 'error' })
  MSW printed: warning
  request:     answered 200 {"source":"network"}
  reached the stand-in API: 1
listen({ onUnhandledFrame: 'error' })
  MSW printed: error
  request:     rejected: [MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledFrame" option.
  reached the stand-in API: 0

The default is warn, which prints and lets the request through. The third case is the one that costs an afternoon. The 2.x to 3.x migration guide lists the MSW 2 option name as renamed, and MSW 3 accepts it without an error and keeps warn. Use onUnhandledFrame, and type-check the setup file so the MSW 2 name fails the build:

npx tsc -p pitfall
pitfall/mocks-v2.js(8,19): error TS2353: Object literal may only specify known properties, and 'onUnhandledRequest' does not exist in type 'PartialObjectDeep<SharedOptions, { recurseIntoArrays: false; allowUndefinedInNonTupleArrays: false; }>'.

The sample’s tsconfig.json sets checkJs, so plain JavaScript setup files get the same check.

In Chromium the same strategy does not reject the call. The worker answered the unhandled GET /api/billing with a 500 carrying MSW’s message, as the record shows. A component that shows an alert for any 500 shows one here too, so a typo in a handler’s URL can pass a test that expects the alert. record.mjs collects the page’s console for that reason, and the [MSW] Error line is the visible sign of the miss.

Every Node test fails with MSW did not answer a request to http://api.example.test. Node is sending fetch to the proxy that NODE_USE_ENV_PROXY and HTTP_PROXY name, so startMocking refuses to start, as the last case of node proxy.mjs shows. Add the API host to NO_PROXY for the test run.

When not to do this

Do not add MSW for one stub in one Playwright spec. page.route does it in the runner you already have, with no worker file to serve and no start-up call to wait for. The browser record shows its cost: the unmatched GET /api/billing reached the server until a catch-all route.abort() was registered before the specific route.3

  await run('Playwright page.route, catch-all abort registered first', '/browser/route.html', async (page) => {
    await page.route('**/api/**', (route) => route.abort())
    await page.route('**/api/user', (route) =>
      route.fulfill({ status: 500, json: { error: 'upstream unavailable' } }),
    )
  })

Do not read a green run as proof that the API behaves this way. The handlers return what you wrote, so a renamed field in the real response passes every test here. A contract test against the provider is the check for that.

Do not leave the strategy at its default in CI. A warning in a log nobody reads is how a suite comes to depend on the network.

Last verified

Verified 2026-11-30 against Node 22.23.5, msw 3.0.8 and TypeScript 5.9.3, and in Chromium 158.0.8127.36 through Playwright 1.63.0. Every output block is what the command before it printed. The browser run happens once in record.sh, which commits its output. Cypress was not run, and what this page says of cy.intercept comes from its documentation.

Footnotes

  1. Service workers run only in secure contexts, which the Service Workers specification takes to mean HTTPS, with an allowance for development. The Secure Contexts algorithm counts any host in 127.0.0.0/8 as potentially trustworthy, so the record’s plain HTTP server on 127.0.0.1 qualifies by its address alone. ↩︎ Back to text

  2. The library’s name describes its browser half. In Node no service worker is involved, and the listen() reference explains that the call is synchronous because there are no workers to register. The installed 3.0.8 build lists four interceptors for setupServer, one each for ClientRequest, XMLHttpRequest, fetch and WebSocket. ↩︎ Back to text

  3. When routes overlap, the page.route reference gives precedence to the route registered last, so a catch-all goes in first to be consulted last. The same page gives HAR replay the opposite default: routeFromHAR aborts a request the file does not hold unless notFound is set to fallback. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.