处理请求

处理拦截的 HTTP 请求的不同方法。

本页将引导你了解在 MSW 中处理拦截请求的所有可能方法。你可以根据自己想要在模拟中实现的目标,选择合适的方法或多种方法的组合。

¥This page will walk you through all the possible ways to handle an intercepted request in MSW. It is up to you to choose the right approach, or a combination of them, based on what you want to achieve in your mocks.

使用模拟响应进行响应

¥Respond with a mocked response

如果你从响应解析器返回一个 Response 实例,该响应将被用作请求的模拟响应。请在此页面了解更多关于模拟响应的信息:

¥If you return a Response instance from the response resolver, that response will be used as the mocked response for the request. Please learn more about mocking responses on this page:

Mocking responses

Declaring and using mocked responses.

直通

¥Passthrough

你可以按原样执行拦截的请求,并通过返回 passthrough() 函数调用的结果来返回其原始响应(即传递请求)。

¥You can perform the intercepted request as-is and return its original response (i.e. passthrough a request) by returning the result of the passthrough() function call.

import { passthrough } from 'msw'
 
http.get('/resource', () => {
  return passthrough()
})

当你只想在特定情况下模拟响应,而其他情况下按原样执行请求时,这尤其有用。

¥This is especially useful when you only want to mock a response in certain situations and perform the request as-is otherwise.

http.get('https://api.example.com/resource', async ({ request }) => {
  const data = await request.clone().json()
 
  if (data?.id === 'abc-123') {
    return HttpResponse.json({ id: 'abc-123' })
  }
 
  return passthrough()
})

以上,你可以拦截请求,将其正文解析为 JSON,然后决定是否要使用模拟响应或按原样执行。

¥Above, you can intercept a request, parse its body as JSON, and then decide whether you want to respond with a mock or perform it as-is.

不返回任何内容

¥Return nothing

你也可以从响应解析器显式或隐式地返回任何内容。如果发生这种情况,MSW 将继续寻找可能与该请求匹配的其他请求处理程序。你可以将其用于网络自检或任何其他不涉及响应请求的副作用。

¥You can also return nothing from the response resolver, either explicitly or implicitly. If that happens, MSW will continue to look for other request handlers that might match ths request. You can utilize this for network introspection or any other side effects that do not involve responding to the request.

export const handlers = [
  http.get('/resource', ({ request }) => {
    console.log('Request intercepted!', request.method, request.url)
  }),
  http.get('/resource', () => {
    return HttpResponse.text('hello world')
  }),
]

在此示例中,第一个请求处理程序将匹配,将消息记录到控制台,并且由于它不返回任何内容,因此完成。例如,第二个请求处理程序将匹配相同的请求,并使用模拟响应进行处理。

¥In this example, the first request handler will match, log the message to the console, and, since it returns nothing, finish. The second request hander will then match the same request and handle it with a mocked response, as an example.