delay

控制响应时间。

默认情况下,MSW 不会延迟任何模拟响应,因此它们几乎会立即到达。在某些情况下,这种行为可能不是所希望的,例如测试服务器延迟或请求超时,因为它不反映现实世界的客户端-服务器通信。

¥By default, MSW does not delay any mocked responses, so they arrive nearly instantaneously. This behavior may not be desired in certain scenarios, like testing server latency or request timeouts, as it doesn’t reflect the real-world client-server communication.

调用签名

¥Call signature

function delay(duration?: number): Promise<void> {}
function delay(mode?: 'real' | 'infinite'): Promise<void> {}

delay.ts

Source code for the `delay` function.

隐式延迟

¥Implicit delay

当不带任何参数调用时,delay 函数将应用实际的服务器响应时间。它是一个随机数,等于与实际 HTTP 服务器通信时遇到的平均响应时间(~100-400ms)。

¥When invoked without any arguments, the delay function applies a realistic server response time. It’s a random number equal to the average response time you encounter when communicating with an actual HTTP server (~100-400ms).

import { http, delay, HttpResponse } from 'msw'
 
export const handlers = [
  http.put('/books/:bookId', async () => {
    // Await a random realistic server response time.
    await delay()
 
    return HttpResponse.json({ id: 'abc-123' })
  }),
]

请注意,在 Node.js 中测试时,隐式延迟被否定以防止它影响测试性能。如果你希望延迟 Node.js 中的响应,请使用以下选项之一。

¥Note that when testing in Node.js, the implicit delay is negated to prevent it affecting the test performance. If you wish to delay responses in Node.js, please use one of the options below.

显式延迟

¥Explicit delay

你可以提供以毫秒为单位的精确延迟持续时间:

¥You can provide an exact delay duration in milliseconds:

import { http, delay, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('/user', async () => {
    // Wait for 1000ms before responding.
    await delay(1000)
 
    return new HttpResponse(null, { status: 404 })
  }),
]

模拟响应流时,控制精确的延迟时间非常方便:

¥Controlling precise delay timing is handy when mocking response streams:

import { http, delay, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('/video', () => {
    const stream = new ReadableStream({
      async start(controller) {
        controller.enqueue(new Uint8Array([1, 2, 3]))
        await delay(1000)
 
        controller.enqueue(new Uint8Array([4, 5, 6]))
        await delay(200)
 
        controller.enqueue(new Uint8Array([7, 8, 9]))
        controller.close()
      },
    })
 
    return new HttpResponse(stream, {
      headers: {
        'Content-Type': 'video/mp4',
      },
    })
  }),
]

延迟模式

¥Delay modes

delay 函数还接受一个字符串,该字符串是代表延迟模式的枚举:

¥The delay function also accepts a string that’s an enum representing a delay mode:

  • "real",明确设置 实际响应时间

    ¥"real", explicitly sets the realistic response time;

  • "infinite",无限期延迟响应,使其永远挂起。

    ¥"infinite", indefinitely delays the response, making it pend forever.

延迟模式对于测试某些服务器响应场景很有用。例如,通过使用 “infinite” 模式,你可以测试应用如何处理响应超时:

¥Delay modes are useful to test certain server response scenarios. For example, by using the “infinite” mode, you can test how your application handles response timeouts:

import { http, delay } from 'msw'
 
export const handlers = [
  http.get('/book/:bookId', async () => {
    // This request will hang indefinitely.
    await delay('infinite')
 
    // And this response will never be sent.
    return new Response()
  }),
]