- Introduction
- Getting started
- Philosophy
- Comparison
- Limitations
- Debugging runbook
- FAQ
- Basics
- Concepts
- Network behavior
- Integrations
- API
- CLI
- Best practices
- Recipes
- Cookies
- Query parameters
- Response patching
- Polling
- Streaming
- Network errors
- File uploads
- Responding with binary
- Custom worker script location
- Global response delay
- GraphQL query batching
- Higher-order resolver
- Keeping mocks in sync
- Merging Service Workers
- Mock GraphQL schema
- Using CDN
- Using custom "homepage" property
- Using local HTTPS
setupWorker
Configure the interception of requests in a browser.
The setupWorker()
function prepares the client-worker communication channel to enable API mocking in the browser.
Call signature
The setupWorker()
function expects an optional list of Request handlers spread as its arguments and returns a Worker instance.
When called without any arguments, the function will return you a worker instance that has no network description (i.e. no request handlers). Use the methods like worker.use()
and worker.resetHandlers()
to add and remove runtime request handlers to the worker instance.
import { setupWorker } from 'msw/browser'
const worker = setupWorker()
// worker.start()
// worker.use(...handlers)
However, if you provide request handlers as the spread argument to the setupWorker()
function, those handlers will be considered initial and will always persist on the worker instance even when resetting the handlers (learn how to opt-out from this here).
import { http, HttpResponse } from 'msw'
import { setupWorker } from 'msw/browser'
const worker = setupWorker(
http.get('/resource', () => HttpResponse.json({ id: 'abc-123' }))
)
Worker instance
The setupWorker()
function returns you a worker instance that is an object you can use to control API mocking in the current browser environment. Below, you can see the list of methods available on the worker instance.