请求处理程序

请求处理程序是一个描述要拦截哪些请求以及如何处理它们的函数。

¥Request handler is a function that describes which requests to intercept and how to handle them.

你应该将请求处理程序视为你在服务器上定义的路由处理程序。例如,这是一个使用 Express 编写的路由处理程序:

¥You should think of request handlers as route handlers you define on the server. For example, here’s a route handler written using Express:

import express from 'express'
 
const app = express()
 
// This route handler instructs Express to handle
// a "GET /user" request by returning a JSON response.
app.get('/user', (req, res) => {
  res.json({ name: 'John' })
})

这是使用 Mock Service Worker 针对相同资源的请求处理程序:

¥And here’s a request handler for the same resource using Mock Service Worker:

import { http, HttpResponse } from 'msw'
 
export const handlers = [
  // And here's a request handler with MSW
  // for the same "GET /user" request that
  // responds with a mock JSON response.
  http.get('/user', ({ request }) => {
    return HttpResponse.json({ name: 'John' })
  }),
]

你可以发现这两个示例之间的一些相似之处:

¥You can spot a few similarities between these two examples:

  1. 它们描述请求的方法(app.get/http.get)和资源路径("/user");

    ¥They describe the request’s method (app.get/http.get) and the resource path ("/user");

  2. 它们接受处理传入请求的解析器​​函数。

    ¥They accept a resolver function that handles incoming requests.

这正是使用 MSW 描述网络行为所需的两件事。然而,与服务器端路由的相似性并非巧合。使用该库时,你需要从服务器的角度描述如何处理请求,因为在实际应用中,服务器层控制请求解析。当然,使用 MSW 时没有服务器。

¥Those are precisely two things needed to describe the network behavior with MSW. This similarity with the server-side routes, however, is not coincidental. When using the library, you describe how to handle requests from the server’s perspective because in the actual application it’s the server layer that controls request resolution. Of course, there are no servers when using MSW.

使用请求处理程序

¥Using request handlers

你使用请求处理程序来描述你想要的网络。MSW 带有内置的 httpgraphql 命名空间,分别用于为 HTTP 和 GraphQL 请求创建请求处理程序。

¥You use request handlers to describe the network you want. MSW comes with built-in http and graphql namespaces to create request handlers for HTTP and GraphQL requests respectively.

通过以下链接了解有关使用这些命名空间的更多信息:

¥Learn more about using those namespaces by following the links below:

执行顺序

¥Execution order

请求处理程序按照定义的顺序从左到右执行。如果多个请求处理程序匹配同一个请求,MSW 将继续对它们进行迭代,直到任何处理程序返回有关如何处理该请求的 明确指令

¥Request handlers execute in the order they have been defined, left-to-right. If multiple request handlers match the same request, MSW will keep iterating over them until any handler returns an explicit instruction on how to handle that request.

import { http, HttpResponse, passthrough } from 'msw'
 
export const handlers = [
  // This handler will be called first but since
  // it doesn't return anything from its resolver,
  // MSW will continue looking for a handler that does.
  http.get('/user', ({ request }) => {
    console.log('Just observing:', request.method, request.url)
  }),
 
  // This handler is called next (2nd), and it returns
  // a JSON response from its resolver. MSW will stop looking
  // for handlers and will consider this one to be relevant
  // to the intercepted request.
  http.get('/user', () => {
    return HttpResponse.json({ name: 'John' })
  }),
 
  // Although this handler also matches the request,
  // it will never be called because the previous handler
  // returned a mocked response.
  http.get('/user', () => passthrough()),
]

在声明网络行为时,了解处理程序的执行顺序非常重要。你可以声明将首先触发的处理程序,观察流量,然后声明负责产生响应的处理程序。

¥Understanding the handler execution order is important when declaring your network behavior. You can declare handlers that will trigger first, observing the traffic, followed by the handlers responsible for yielding responses.

正确构造你的请求处理程序是区分模糊资源的关键:

¥Correctly structuring your request handlers is the key to differentiate between ambiguous resources:

export const handlers = [
  // By placing a more specific pathname first,
  // the "GET /user/messages" request will be handled
  // properly, despite it also matching a more permissive
  // handler below.
  http.get('/user/messages', messagesResolver)
  http.get('/user/*', resolverOne),
]

自定义请求处理程序

¥Custom request handlers

在某些情况下,你可能需要更精细的请求处理体验。你可以创建自定义请求处理程序来处理这些情况。

¥In certain situations, you may want a more fine-tuned request handling experience. You can create custom request handlers to cover those situations.

请参阅以下 RequestHandler API 以了解有关创建自定义请求处理程序的更多信息:

¥Please see the following RequestHandler API to learn more about creating custom request handlers:

RequestHandler

API reference for the `RequestHandler` class.

相关材料

¥Related materials