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'23const worker = setupWorker(4 rest.get('https://api.github.com/users/:username', async (req, res, ctx) => {5 // Perform an original request to the intercepted request URL6 const originalResponse = await ctx.fetch(req)7 const originalResponseData = await originalResponse.json()89 return res(10 ctx.json({11 location: originalResponseData.location,12 firstName: 'Not the real first name',13 }),14 )15 }),16)1718worker.start()
It is highly recommended to use
ctx.fetch()
instead of a regularwindow.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 regularwindow.fetch()
are subjected to mocking.
Request
Response
Body
1{2 // Resolved from the original response3 "location": "San Francisco",4 "firstName": "Not the real first name"5}