拦截请求
了解如何拦截传出的请求。
要检查和处理传出的请求,你必须先拦截它们。在 MSW 中,你可以通过定义称为请求处理程序的函数来实现此目的。以下是一个例子:
¥To inspect and handle outgoing requests you have to intercept them first. In MSW, you do that by defining functions called request handlers. Here’s an example of one:
http.get('/resource', ({ request }) => {
console.log(request.method, request.url)
})
这是一个请求处理程序,它将拦截所有
GET /resource
请求并将其信息打印到控制台。¥This is a request handler that will intercept all
GET /resource
requests and print their information to the console.
本页将帮助你熟悉请求处理程序的结构以及支持的 HTTP 请求拦截方式。请参阅本节中关于特定用例和最佳实践的其他资源。
¥This page will get you familiar with the structure of request handlers and the supported ways of intercepting HTTP requests. Please refer to additional resources in this section on particular use cases and best practices.
请求处理程序剖析
¥Anatomy of a request handler
每个请求处理程序都包含两部分:谓词和响应解析器。
¥Every request handler consists of two parts: a predicate and a response resolver.
// 👇 This is a predicate.
http.get('/resource', () => {})
// 👆 This is a resolver.
谓词决定拦截哪些请求,解析器决定如何处理这些请求。在本页面,我们将介绍为请求处理程序定义谓词的不同方法。你可以在 “模拟响应” 部分了解更多关于处理请求的信息:
¥A predicate decides which requests to intercept, and a resolver decides what to do with those requests. On this page, we will take a look at the different ways to define a predicate for your request handlers. You can learn more about handling requests in the “Mocked responses” section:
Handling requests
Different ways to handle an intercepted request.
谓词
¥Predicate
请求 URL
¥Request URL
你可以提供一个字符串作为请求处理程序谓词,该字符串表示整个请求 URL 或其部分。MSW 将使用 path-to-regexp@6
来匹配你的谓词和传出请求,以确定它们是否匹配。我们强烈建议你熟悉该库的功能集。
¥You can provide a string as a request handler predicate that represents an entire request URL or its portion. MSW will use path-to-regexp@6
to match your predicate against outgoing requests to determine if they match. We highly recommend you familiarize yourself with the feature set of that library.
相对 URL
¥Relative URL
当你提供相对请求 URL 作为谓词时,它将根据当前文档 (document.baseUri
) 进行解析。这对于浏览器内模拟非常方便,但请记住,你需要在 Node.js 测试中配置基本 URL,因为 Node.js 中没有此功能。
¥When you provide a relative request URL as a predicate, it will be resolved against the current document (document.baseUri
). This is handy for in-browser mocking, but bear in mind that you need to configure the base URL in your Node.js tests because that’s not a thing in Node.js.
http.get('/users/:id', () => {})
假设你的应用在
http://localhost:3000
上运行,则此请求处理程序将匹配GET http://localhost:3000/users/abc-123
请求。¥This request handler will match the
GET http://localhost:3000/users/abc-123
request, given your application is running athttp://localhost:3000
.
查询/搜索参数
¥Query/search parameters
查询参数不描述资源路径,而是随请求发送的附加数据。因此,它们不能出现在请求谓词中。任何意外包含在请求谓词中的查询参数都将被自动删除,并且不会影响 URL 匹配。
¥Query parameters do not describe resource paths but rather additional data sent with the request. As such, they must not be present in the request predicate. Any query parameters accidentally included in the request predicate will automatically be removed and have no effect on the URL matching.
你拦截的请求仍然可以包含查询参数,并且你可以在响应解析器中访问它们。在此页面上了解更多信息:
¥You intercepted requests can still have query parameters, and you can access them in the response resolver. Learn more about how on this page:
Query parameters
Read and write request query parameters.
绝对 URL
¥Absolute URL
当你提供绝对请求 URL 作为谓词时,传出的请求必须与其方案、主机和路径名匹配才能触发请求处理程序。
¥When you provide an absolute request URL as a predicate, the outgoing request must match its scheme, host, and pathname to trigger the request handler.
http.post('https://api.github.com/repos/:owner/:repo', () => {})
特殊标记
¥Special tokens
使用字符串请求谓词时,你可以在其中包含特殊标记来表示不同的匹配行为:
¥When using a string request predicate, you can include special tokens in it to represent different matching behaviors:
-
*
(通配符),用于匹配任意 URL 或其中的部分 URL;¥
*
(wildcard), to match any URL or a portion of the URL in its place; -
:foo
(参数),用于匹配 URL 中的命名参数(参见 路径参数)。¥
:foo
(parameter), to match a named parameter in the URL (see Path parameters).
正则表达式
¥Regular expression
你可以提供正则表达式作为请求处理程序谓词。MSW 将根据传出的请求 URL 测试它,以确定它们是否匹配。
¥You can provide a regular expression as a request handler predicate. MSW will test it against the outgoing request URLs to determine if they match.
http.get(/\/settings\/(profile|settings)/, () => {})
通常建议使用请求路径/URL 谓词,但对于最复杂的匹配场景,你也可以使用正则表达式。
¥It’s generally recommended to use request paths/URLs predicates, but you can rely on regular expressions for the most complex matching scenarios.
响应解析器
¥Response resolver
响应解析器对象参数中为 http.*
处理程序提供了以下属性:
¥The following properties are available on the response resolver object argument for http.*
handlers:
属性 | 类型 | 描述 |
---|---|---|
request | Request | 获取拦截请求的 API Request 表示。 |
requestId | string | 代表被拦截请求的 UUID。 |
params | Record<string, string | string[]> | 请求 路径参数(例如 :userId )。 |
cookies | Record<string, string> | 已解析 请求 cookie。 |
http.get('/resource', ({ request, params, cookies }) => {})
后续步骤
¥Next steps
现在你已经了解了如何拦截 HTTP 请求,接下来学习如何处理它们的响应:
¥Now that you know how to intercept HTTP requests, proceed by learning how to handle their responses:
Mocking responses
Different ways to handle an intercepted HTTP request.