Mock Service Worker
  1. Recipes
  2. Response patching

Response patching

Response patching is a technique when a mocked response is based on the actual response. This technique may be useful when working with an existing API with an intention to augment it for various purposes (i.e., experimenting or debugging).

Pass the intercepted request object to the ctx.fetch() call to get the original response. Using ctx.fetch() performs a request that bypasses any request handlers, as any window.fetch() calls, even those inside response resolvers, are subjected to interception.

Examples

Below is an example of patching a response from a user detail endpoint of GitHub API v3.

1import { setupWorker, rest } from 'msw'
2
3const worker = setupWorker(
4 rest.get('https://api.github.com/users/:username', async (req, res, ctx) => {
5 // Perform an original request to the intercepted request URL
6 const originalResponse = await ctx.fetch(req)
7 const originalResponseData = await originalResponse.json()
8
9 return res(
10 ctx.json({
11 location: originalResponseData.location,
12 firstName: 'Not the real first name',
13 }),
14 )
15 }),
16)
17
18worker.start()

It is highly recommended to use ctx.fetch() instead of a regular window.fetch() within response resolvers, because it prevents actual requests from being matched against the MSW mocks definition.

You may use window.fetch() intentionally, for example, when you need to perform a request that is later mocked as a part of another response resolver. Requests issued by regular window.fetch() are subjected to mocking.

Request

GEThttps://api.github.com/users/octocat

Response

200OK
Body
1{
2 // Resolved from the original response
3 "location": "San Francisco",
4 "firstName": "Not the real first name"
5}