响应修补

结合原始和模拟响应。

响应修补是一种将模拟响应与实际响应相结合的技术。这种技术在使用现有 API(包括第三方 API)时特别有用,因为它允许动态增强其响应。

¥Response patching is a technique to combine a mocked response with the real response. This technique is particularly useful when working with existing API (including third-party API) as it allows to augment its responses on the fly.

要获取对被拦截请求的原始响应,你必须按原样执行它。如果你在处理程序中使用普通的 fetch() 函数,它将分派一个请求,该请求将再次匹配相同的处理程序,从而导致无限请求循环。相反,使用 bypass() 实用函数,它将标记任何给定的 Request 实例为任何其他匹配的请求处理程序要绕过的实例。

¥To get the original response to the intercepted request you have to perform it as-is. If you use the plain fetch() function in the handler, it will dispatch a request that will again match the same handler, causing an infinite request loop. Instead, use the bypass() utility function that will mark any given Request instance as the one to be bypassed by any otherwise matching request handlers.

import { http, bypass, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('https://api.github.com/user/:username', async ({ request }) => {
    // Fetch the original response from the GitHub API.
    const gitHubUser = await fetch(bypass(request)).then((response) =>
      response.json()
    )
 
    // Respond with a mocked response that combines
    // the actual and mock data.
    return HttpResponse.json({
      id: gitHubUser.id,
      login: gitHubUser.login,
      location: 'London',
    })
  }),
]

bypass

API reference for the `bypass` function.

代理请求

¥Proxying requests

你可以通过构建设计的代理 Request 实例来代理传出请求。

¥You can proxy outgoing requests by constructing a designed proxy Request instance.

import { http, bypass } from 'msw'
 
export const handlers = [
  http.get('/resource', async ({ request }) => {
    const originalUrl = new URL(request.url)
    const proxyUrl = new URL('/proxy', location.origin)
 
    // Construct a proxy request.
    const proxyRequest = new Request(proxyUrl, {
      headers: {
        'Content-Type': request.headers.get('Content-Type'),
        'X-Proxy-Header': 'true',
      },
    })
 
    // Perform the proxy request.
    const originalResponse = await fetch(bypass(proxyRequest))
 
    // Return the mocked response...
  }),
]