使用二进制响应

提供 ArrayBuffer 作为模拟响应主体,以使用该二进制数据进行响应。

¥Provide the ArrayBuffer as the mocked response body to respond with that binary data.

浏览器

¥Browser

import { http, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('/images/:imageId', async ({ params }) => {
    // The easiest way to obtain a buffer in the browser
    // is to fetch the resource you need and read its body
    // as "response.arrayBuffer()".
    const buffer = await fetch(`/static/images/${params.imageId}`).then(
      (response) => response.arrayBuffer()
    )
 
    // Use the "HttpResponse.arrayBuffer()" shorthand method
    // to automatically infer the response body buffer's length.
    return HttpResponse.arrayBuffer(buffer, {
      headers: {
        'Content-Type': 'image/jpeg',
      },
    })
  }),
]

不要忘记在 Content-Type 响应标头中描述响应主体的 MIME 类型。

¥Don’t forget to describe the MIME type of your response body in the Content-Type response header.

Node.js

你也可以使用 fetch() 请求资源并在 Node.js 中将它们读取为 ArrayBuffer。但是,你还可以读取文件系统中的任何文件并使用其二进制文件进行响应。

¥You can use fetch() to request resources and read them as ArrayBuffer in Node.js as well. However, you can also read any file in your file system and respond with its binary.

import fs from 'node:fs'
import path from 'node:path'
import { http, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('/videos/:videoId', async ({ params }) => {
    // Read a video file from the file system.
    const buffer = fs.readFileSync(
      path.resolve(process.cwd(), 'mock-assets/videos', `${videoId}.mp4`)
    )
 
    return HttpResponse.arrayBuffer(buffer, {
      headers: {
        'Content-Type': 'video/mp4',
      },
    })
  }),
]