mswMock Service Worker

start()

Registers and activates the Service Worker instance responsible for intercepting requests.

Options

serviceWorker

url

  • string (default: "/mockServiceWorker.js")

Custom Service Worker registration URL.

1const worker = setupWorker(...)
2
3worker.start({
4 serviceWorker: {
5 // Points to the custom location of the Service Worker file.
6 url: '/assets/mockServiceWorker.js'
7 }
8})
Note that the url path is relative to the server's root directory.

options

  • RegistrationOptions

Custom Service Worker registration options.

1const worker = setupWorker(...)
2
3worker.start({
4 serviceWorker: {
5 options: {
6 // Narrow the scope of the Service Worker to intercept requests
7 // only from pages under this path.
8 scope: '/product'
9 }
10 }
11})

quiet

  • boolean (default: false)

Disables the logging of matched requests in a browser's console.

1const worker = setupWorker(...)
2
3worker.start({
4 quiet: true,
5})

waitUntilReady

  • boolean (default: true)

Defers any application requests that happened while Service Worker was activating.

Disabling this behavior is not recommended, as that would create a race condition between the Service Worker registration and your application's runtime.

findWorker

  • (scriptURL, mockServiceWorkerUrl) => boolean

A custom lookup function to find a Mock Service Worker in the list of all registered Service Workers on the page.

1const worker = setupWorker(...)
2
3worker.start({
4 // Return the first registered service worker found with the name
5 // of `mockServiceWorker`, disregarding all other parts of the URL
6 findWorker: (scriptURL, _mockServiceWorkerUrl) => scriptURL.includes('mockServiceWorker'),
7})
Most applications should not need to use this option, but it may be useful in the scenario that your application runs behind a proxy, or has a dynamic hostname.

onUnhandledRequest

  • "bypass" | "warn" | "error" | (req: MockedRequest) => void
  • (default: "warn")

Specifies how to handle a request that is not listed in the request handlers.

Pre-defined behaviors

Option nameDescription
"bypass"Performs an unhandled request as-is.
"warn"Produces a warning in the browser's console.
"error"Produces an error in the browser's console.
1const worker = setupWorker(
2 rest.get('/books', (req, res, ctx) => {
3 return res(ctx.json({ title: 'The Lord of the Rings' }))
4 }),
5)
6
7worker.start({
8 onUnhandledRequest: 'warn',
9})

Custom callback

When passed a function as a value of this option, the library executes that function whenever an unhandled request occurs. The behavior of such unhandled request won't be affected, but can be prevented if the custom callback function throws an exception.

1const worker = setupWorker(
2 rest.get('/books', (req, res, ctx) => {
3 return res(ctx.json({ title: 'The Lord of the Rings' }))
4 }),
5)
6
7worker.start({
8 onUnhandledRequest(req) {
9 console.error(
10 'Found an unhandled %s request to %s',
11 req.method,
12 req.url.href,
13 )
14 },
15})

Operation

Reusing worker

When start() is called, it looks up an existing worker instance for the given client, and updates it, if found.

Registering worker

When there is no worker instance controlling the current client, it registers a new Service Worker from the given StartOptions.url for the StartOptions.scope. Upon registration, the worker signals that its readiness to the client, which enables the mocking.

Integrity check

Mock Service Worker distributes the Service Worker JavaScript module (mockServiceWorker.js) that is responsible for requests interception. However, since it's not technically possible to register the worker from node_modules directory, the library exposes a designated CLI to copy the worker file into your public directory. This makes the worker file an external dependency of the library. The worker file itself is subjected to improvements and bug fixes, yet since it's not linked to the library's distributive, the is no way to implicitly apply any updates, or even know when such are necessary.

To handle this, the library uses a concept of integrity check. There is an MD5 hash string generated from the worker's file content that is distributed inside the worker. When the start() function is called, it compares the integrity checksum between the currently registered worker (in your public directory) and the latest published worker file (from node_modules). Whenever there is a mismatch between the checksums, it prints an error and suggests to update your local copy of the worker file to ensure you have all the latest changes.

Clients map

Internally, the worker file keeps a map of all controlled clients. This allows to control mocking per-client (page) basis, allowing one tab of the same project to have mocking, while the other doesn't.

Whenever a client is closed, it communicates the close event to the worker. When the last client is closed, the worker unregisters itself to prevent affecting unrelated pages on the same host.

Usage

1// src/mocks.js
2import { setupWorker } from 'msw'
3
4const worker = setupWorker(...mocks)
5worker.start()