Mock Service Worker

Life-cycle events

The life-cycle events API is designed to execute arbitrary logic in response to internal MSW events, such as the start and end of a request, or the mocked/original response. This is primarily useful for third-party extension developers, or while debugging request handlers.

This API is not meant for mocking. Use setupWorker/setupServer instead.

Events list

Request events

1// A new request has been dispatched.
2worker.on('request:start', (req) => {})
3// Request has a corresponding request handler.
4worker.on('request:match', (req) => {})
5// Request doesn't have any corresponding request handlers.
6worker.on('request:unhandled', (req) => {})
7// Request has concluded (regardless of the response).
8worker.on('request:end', (req) => {})

Response events

1// Mocked response has been sent to a request with a given `reqId`.
2worker.on('response:mocked', (res, reqId) => {})
3// Original response has been sent to a request with a given `reqId`.
4worker.on('response:bypass', (res, reqId) => {})

The same events can be listened to on a server instance of setupServer.

Tracking a request

Each life-cycle event emits in isolation. To connect multiple events with a single request, the library exposes a request ID (reqId)—a UUID that persists with a specific request.

1const allRequests = new Map()
2
3worker.on('request:start', (req) => {
4 const { id } = req
5 // Store this request by id in an internal Map.
6 allRequests.set(id, req)
7})
8
9worker.on('response:mocked', (res, reqId) => {
10 // Get a request associated with this response.
11 const req = allRequests.get(reqId)
12})