流式传输

使用模拟数据流进行响应。

你可以通过构建 ReadableStream 实例并将其作为模拟响应的主体,使用数据流来响应拦截的请求。

¥You can respond to the intercepted request with a stream of data by constructing a ReadableStream instance and providing it as the body of a mocked response.

http.get('/stream', () => {
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue(new TextEncoder().encode('hello'))
      controller.enqueue(new TextEncoder().encode('world'))
      controller.close()
    },
  })
 
  return new HttpResponse(stream, {
    headers: {
      'content-type': 'text/plain',
    },
  })
})

转换流

¥Transform streams

你可以使用 Fetch API 支持的任何类型的 Web 流作为模拟响应主体,例如 TransformStream。以下是获取原始响应流并使用 TransformStream 在其块之间注入延迟的复合场景:

¥You can use any kind of Web Stream supported by the Fetch API as a mocked response body, like a TransformStream, for example. Here’s a compound scenario of fetching the original response stream and injecting latency between its chunks using TransformStream:

import { http, HttpResponse, delay } from 'msw'
 
http.get('/video/:id', async ({ params }) => {
  const videoResponse = await fetch(
    `https://api.example.com/videos/${params.id}`,
  )
  const videoStream = videoResponse.body
 
  const latencyStream = new TransformStream({
    start() {},
    async transform(chunk, controller) {
      await delay(1000)
      controller.enqueue(chunk)
    },
  })
 
  return new HttpResponse(videoStream.pipeThrough(latencyStream), videoResponse)
})

了解更多关于使用响应计时的信息:

¥Learn more about using response timing:

Response timing

Control server response time.