高阶解析器
创建高阶解析器是管理模拟响应的动态且通常重复的性质的好方法。由于 响应解析器 是一个常规函数,你可以从可以自定义解析器行为的高阶函数中返回它。
¥Creating a higher-order resolver is a good way of managing the dynamic, and often repetitive, nature of the mocked responses. Since Response resolver is a regular function, you can return it from a higher-order function that can customize the resolver’s behavior.
例如,你可以这样描述受保护的路由:
¥For example, this is how you can describe protected routes:
// mocks/middleware.js
import { HttpResponse } from 'msw'
// A higher-order response resolver that validates
// the request authorization header before proceeding
// with the actual response resolver.
export function withAuth(resolver) {
return (input) => {
const { request } = input
if (!request.headers.get('Authorization')) {
return new HttpResponse(null, { status: 401 })
}
return resolver(input)
}
}
// mocks/handlers.js
import { http, HttpResponse } from 'msw'
import { withAuth } from './middleware'
export const handlers = [
// Using the "withAuth" higher-order response resolver
// will require the outgoing requests to "POST /comment"
// to have the "Authorization" header set before it returns
// a mocked JSON response.
http.post('/comment', withAuth(({ request }) => {
const { author, text } = await request.json()
return HttpResponse.json({ author, text }, { status: 201 })
}))
]