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.

Methods