响应时长
控制服务器响应时间。
你可以使用 MSW 中的 delay()
函数来控制处理拦截请求时的服务器响应时间。在底层,delay()
函数返回一个承诺,该承诺会在一定时间后解析。
¥You can control the server response time when handling intercepted requests using the delay()
function from MSW. Under the hood, the delay()
function returns a promise that resolves after a certain amount of time.
import { http, HttpResponse, delay } from 'msw'
http.get('/resource', async () => {
await delay(500)
return HttpResponse.json({ id: 'abc-123' })
})
此处,
GET /resource
请求至少需要 500 毫秒才能返回给定的模拟响应。请记住,响应解析器评估时间并非影响响应时间的唯一因素。¥Here, the
GET /resource
request will take at least 500ms to respond with the given mocked response. Remember that the response resolver evaluation time isn’t the only factor that affects the response timing.
了解更多关于使用 delay()
API、其默认行为及其支持的延迟模式的信息:
¥Learn more about using the delay()
API, its default behavior, and the delay modes it supports:
delay()
API reference for the `delay` function.
流延迟
¥Stream latency
你可以在响应解析期间的任何位置使用 delay()
,包括在 使用流进行响应 流式传输的块之间:
¥You can use delay()
anywhere during the response resolution, including in-between the streamed chunks if responding with a stream:
http.get('/stream', () => {
const stream = new ReadableStream({
async start(controller) {
controller.enqueue(new TextEncoder().encode('hello'))
await delay(200)
controller.enqueue(new TextEncoder().encode('world'))
await delay(300)
controller.close()
},
})
return new HttpResponse(stream, { ... })
})
全局延迟
¥Global delay
有时你可能想要引入一个影响所有请求的延迟。你可以通过几种方法实现这一点。
¥Sometimes you might want to introduce a delay that affects all requests. There are a few ways you can achieve that.
选项 1:延迟 fallthrough 处理程序
¥Option 1: Delay fallthrough handler
利用请求处理程序的执行顺序,引入一个除了等待其他处理程序执行延迟之外什么都不做的请求处理程序:
¥Take advantage of the request handler execution order and introduce a request handler that does nothing but awaits a delay before any other handlers:
export const handlers = [
http.all('*', async () => {
await delay(500)
}),
// ...other request handlers.
]
选项 2:高阶解析器
¥Option 2: Higher-order resolver
另一种选择是定义一个高阶响应解析器,它封装了延迟逻辑,并选择性地将其应用于某些响应解析器。
¥Another option would be to define a higher-order response resolver that encapsulates the delay logic and applies it selectively to some response resolvers.
// with-delay.ts
import { delay, type HttpResponseResolver } from 'msw'
export async function withDelay(resolver: HttpResponseResolver) {
return async (...args) => {
// Provide no arguments to the `delay` function
// to apply a random realistic response time.
await delay()
return resolver(...args)
}
}
// handlers.ts
import { withDelay } from './with-delay'
export const handlers = [
http.get(
'/user',
withDelay(({ request }) => {
return HttpResponse.json({ id: 'abc-123' })
}),
),
http.post(
'/cart/:cartId',
withDelay(() => {
return new HttpResponse(null, { status: 201 })
}),
),
http.get('/products', () => {
return HttpResponse.json([1, 2, 3])
}),
]