RequestHandler
请求处理程序实现的基类。
此类用于创建自定义请求处理程序。在创建自定义请求处理程序之前,请优先使用标准 http
和 graphql
命名空间。
¥This class is meant for creating custom request handlers. Please prefer using
the standard http
and graphql
namespaces before creating a custom request handler.
调用签名
¥Call signature
import { RequestHandler } from 'msw'
export class CustomRequestHandler extends RequestHandler {
constructor() {
super(args)
}
}
RequestHandler
类构造函数需要一个具有以下属性的单个 args
对象:
¥The RequestHandler
class constructor expects a single args
object with the following properties:
参数名称 | 类型 | 描述 |
---|---|---|
info | object | 请求处理程序 information 对象。 |
resolver | Function | 响应解析器 函数用于处理匹配的请求。 |
options | object | 可选。请求处理程序 options。 |
请求处理程序选项
¥Request handler options
once
-
可选。
Boolean
。¥Optional.
Boolean
.
设置为 true
时,在第一个之后将此请求处理程序标记为不活动…
¥When set to true
, marks this request handler as inactive after the first …
属性
¥Properties
info
object
。
有关此请求处理程序的信息对象。
¥Information object about this request handler.
属性名称 | 类型 | 描述 |
---|---|---|
header | string | 此请求处理程序的公共字符串表示。 |
callFrame | string | 此请求处理程序调用的最顶层框架。对调试有用。 |
请求处理程序实例上的 info
对象还将合并你作为 info
参数提供给 RequestHandler
构造函数的任何对象。
¥The info
object on the request handler instance will also merge whatever object you provide as the info
argument to the RequestHandler
constructor.
class MyHandler extends RequestHandler {
constructor(method, path, resolver) {
super({
info: {
// Public representation of this request handler.
// This string will be used when logging the handler
// using the ".log()" method.
header: `${method} ${path}`,
// Additional info properties forwarded from the
// constructor arguments of this custom handler.
method,
path,
},
resolver,
})
}
}
const handler = new MyHandler('GET', '/user')
console.log(handler.info.method) // "GET"
console.log(handler.info.path) // "/user"
info
对象用于表示有关请求处理程序的公共信息。不要将此对象用于内部处理程序上下文。相反,在自定义请求处理程序类上将你需要的任何附加属性声明为私有属性。
¥The info
object is meant for representing public information about the
request handler. Do not use this object for internal handler context. Instead,
declare whichever additional properties you need as private properties on the
custom request handler class.
方法
¥Methods
parse(args)
解析拦截的请求以提取其他信息,用于进一步的请求处理程序阶段。
¥Parses the intercepted request to extract additional information for further request handler phases.
参数名称 | 类型 | 描述 |
---|---|---|
request | Request | 拦截的请求实例。 |
context | object | 请求解析上下文。 |
extendResolverArgs(args)
扩展响应解析器参数对象。从 extendResolverArgs()
方法返回的任何对象都会与默认响应解析器参数对象进行浅合并。
¥Extends the response resolver argument object. Whichever object is returned from the extendResolverArgs()
method gets shallow-merged with the default response resolver argument object.
参数名称 | 类型 | 描述 |
---|---|---|
request | Request | 拦截的请求实例。 |
parsedResult | object | 从 parse() 方法返回的对象。 |
context | object | 请求解析上下文。 |
predicate(args)
决定拦截的请求是否应由此请求处理程序处理。predicate()
方法预计返回一个布尔值。
¥Decides whether the intercepted request should be handled by this request handler. The predicate()
method is expected to return a boolean.
参数名称 | 类型 | 描述 |
---|---|---|
request | Request | 拦截的请求实例。 |
parsedResult | object | 从 parse() 方法返回的对象。 |
context | object | 请求解析上下文。 |
log(args)
每当此请求处理程序处理了拦截的请求时,打印浏览器控制台消息。
¥Prints a browser console message whenever this request handler has handled the intercepted request.
参数名称 | 类型 | 描述 |
---|---|---|
request | Request | 拦截的请求实例。 |
response | Response | 从 resolver 函数返回的响应实例。 |
parsedResult | object | 从 parse() 方法返回的对象。 |
请求阶段
¥Request phases
每当 MSW 拦截请求时,它都会将其传递给请求处理程序。然后,请求处理程序将按以下顺序列出的阶段处理请求:
¥Whenever MSW intercepts a request, it will pass it to the request handler. The request handler will then process the request in phases listed in the following order:
阶段 1:解析
¥Phase 1: Parsing
首先,将使用请求处理程序的 parse()
方法解析被拦截的请求实例。解析阶段旨在从请求中提取附加信息,而这些信息在 Fetch API Request
实例中不可用。
¥First, the intercepted request instance will be parsed using the parse()
method of the request handler. The parsing phase is designed to extract additional information from the request that is otherwise unavailable in the Fetch API Request
instance.
让我们创建一个自定义 SearchParamsHandler
,它将仅处理搜索参数与预期对象匹配的请求。
¥Let’s create a custom SearchParamsHandler
that will only handle requests whose search parameters will match the expected object.
// SearchParamsHandler.js
import { RequestHandler } from 'msw'
export class SearchParamsHandler extends RequestHandler {
constructor(expectedParams, resolver) {
super({
info: { header: JSON.stringify(expectedParams) },
resolver,
})
this.expectedParams = expectedParams
}
parse({ request }) {
// Extract search parameters from the intercepted request URL.
const searchParams = new URL(request.url).searchParams
// Expose the search parameters for the other handler's methods.
return {
searchParams,
}
}
}
阶段 2:谓词
¥Phase 2: Predicate
下一阶段确定拦截的请求是否应由此请求处理程序处理。拦截的请求实例和从 parse()
方法返回的解析结果将传递给请求处理程序的 predicate()
方法。谓词方法必须返回一个布尔值,指示此处理程序是否用于处理被拦截的请求。
¥The next phase determines if the intercepted request should be handled by this request handler. The intercepted request instance and the parsing result returned from the parse()
method are passed to the predicate()
method of the request handler. The predicate method must return a boolean indicating whether this handler is meant to handle the intercepted request.
例如,让我们迭代自定义 SearchParamsHandler
请求处理程序,以仅匹配搜索参数与提供的 expectedParams
对象匹配的拦截请求。
¥For example, let’s iterate on the custom SearchParamsHandler
request handler to only match the intercepted requests whose search parameters match the provided expectedParams
object.
// SearchParamsHandler.js
import { RequestHandler } from 'msw'
export class SearchParamsHandler extends RequestHandler {
constructor(expectedParams, resolver) {
super({
info: { header: JSON.stringify(expectedParams) },
resolver,
})
this.expectedParams = expectedParams
}
parse({ request }) {
const searchParams = new URL(request.url).searchParams
return {
searchParams,
}
}
predicate({ request, parsedResult }) {
const { searchParams } = parsedResult
// Iterate over the expected search parameters and
// make sure that the actual request matches them.
for (const [expectedParamName, expectedParamValue] of Object.entries(
this.expectedParams
)) {
if (searchParams.get(expectedParamName) !== expectedParamValue) {
return false
}
}
return true
}
}
短语 3:解析
¥Phrase 3: Resolution
如果请求处理程序在谓词阶段返回 true
,则解析阶段开始。父 RequestHandler
类通过使用 request
实例和从 extendResolverArgs()
方法返回的任何附加信息执行提供的 resolver
函数来处理请求解析。解析器函数返回的响应将传播到 MSW 并将其应用于请求。
¥If the request handler returned true
in the predicate phase, the resolution phase begins. The parent RequestHandler
class handles the request resolution by executing the provided resolver
function with the request
instance and whichever additional information returned from the extendResolverArgs()
method. The response returned from the resolver function is propagated to MSW and it applies it to the request.
下面是一个使用 extendResolverArgs()
方法从被拦截请求的 URL 中提取 URLSearchParams
并将它们作为响应解析器参数上的附加数据公开的示例。
¥Here’s an example of using the extendResolverArgs()
method to extract URLSearchParams
from the intercepted request’s URL and expose them as additional data on the response resolver argument.
// SearchParamsHandler.js
import { RequestHandler } from 'msw'
export class SearchParamsHandler extends RequestHandler {
constructor(expectedParams, resolver) {
super({
info: { header: JSON.stringify(expectedParams) },
resolver,
})
}
parse({ request }) {
const searchParams = new URL(request.url).searchParams
return {
searchParams,
}
}
predicate({ request, parsedResult }) {
/* Search params predicate here */
}
extendResolverArgs({ request, parsedResult }) {
return {
searchParams: parsedResult.searchParams,
}
}
}
// handlers.js
import { HttpResponse } from 'msw'
import { SearchParamsHandler } from './SearchParamsHandler'
export const handlers = [
new SearchParamsHandler({ id: 'abc-123' }, ({ request, searchParams }) => {
// The custom request handler exposes the reference to
// the "URLSearchParams" instance of the intercepted request
// so we can operate with it directly in the resolver.
const id = searchParams.get('id')
return HttpResponse.json({ id })
}),
]