HttpResponse

HttpResponse 类是 Fetch API Response 的替代品,旨在允许更方便地声明响应并支持其他不可用的功能,如模拟响应 cookie。

¥The HttpResponse class is a drop-in replacement for the Fetch API Response designed to allow for more convenient response declaration and support otherwise unavailable features, like mocking response cookies.

为什么不使用原生 Response

¥Why not native Response?

你绝对可以在响应解析器中使用原生 Fetch API Response 实例。MSW 建立在标准请求和响应原语之上,因此你可以随时使用它们。

¥You can absolutely use the native Fetch API Response instances in your response resolvers. MSW is built on top of the standard request and response primitives, so you can use them any time instead.

但是,HttpResponse 类启用了某些功能,例如模拟响应 cookie,这些功能在使用标准 Response 类时不可用。为了保持一致性,我们强烈建议每天使用 HttpResponse 类。我们承认这是一个特定于库的 API,我们致力于通过尊重默认的 Response 构造函数签名和方法以及尽量减少此类附带的库特定功能的数量来教你有关 Web 基础知识的知识。

¥However, the HttpResponse class enables certain features, like mocking response cookies, which are not available when using the standard Response class. For the sake of consistency, we highly recommend using the HttpResponse class on a daily basis. We acknowledge that it is a library-specific API and we are dedicated to make it teach you about the web fundamentals through respecting the default Response constructor signature and methods as well as minimizing the amount of library-specific features this class ships.

从历史上看,选择是在隐式修补全局 ResponseHeaders 类以在设置 Set-Cookie 标头时建立代理设置器,因为之后无法读取它。我们决定不干预全局变量,因为我们尊重你的应用及其运行环境的完整性,并希望证明 API 模拟可以基于最佳实践和标准 API 构建。

¥Historically, the choice was between implicitly patching the global Response and Headers classes to establish a proxy setter whenever a Set-Cookie header is set, since it cannot be read afterward. We’ve decided not to meddle with the globals because we respect the integrity of your application and the environment it runs in, and want to prove that API mocking can be built on best practices and standard APIs instead.

调用签名

¥Call signature

HttpResponse 类具有与 Fetch API Response 类相同的构造函数签名。这还包括静态响应方法,如 Response.json()Response.error()

¥The HttpResponse class has the identical constructor signature to the Fetch API Response class. This includes the static response methods like Response.json() and Response.error() too.

class HttpResponse {
  constructor(
    body:
      | Blob
      | ArrayBuffer
      | TypedArray
      | DateView
      | FormData
      | ReadableStream
      | URLSearchParams
      | string
      | null
      | undefined
    options?: {
      status?: number
      statusText?: string
      headers?: HeadersInit
    }
  )
}

HttpResponse.ts

Source code for the `HttpResponse` class.

标准方法

¥Standard methods

new HttpResponse(body, init)

使用给定的响应主体和选项构造一个新的 Response 实例。

¥Constructs a new Response instance with the given response body and options.

const response = new HttpResponse('Hello world!')

与常规 Response 构造函数类似,你可以为 HttpResponse 提供响应选项以自定义响应实例:

¥Similar to the regular Response constructor, you can provide HttpResponse with response options to customize the response instance:

// This is synonymous to "new Response()".
new HttpResponse('Not found', {
  status: 404,
  headers: {
    'Content-Type': 'text/plain',
  },
})

请参阅 Response API 以了解有关构建响应的更多信息。

¥Please see the Response API to learn more about constructing responses.

HttpResponse.json(body, init)

使用 JSON 主体创建新响应的静态方法。

¥A static method that creates a new response with the JSON body.

http.get('/resource', () => {
  // This is synonymous to "Response.json(body)".
  return HttpResponse.json({
    id: 'abc-123',
    title: 'Modern Testing Practices',
  })
})

HttpResponse.error()

创建新网络错误响应实例的静态方法。

¥A static method that creates a new network error response instance.

http.get('/resource', () => {
  // This is synonymous to "Response.error()".
  return HttpResponse.error()
})

请注意,HttpResponse.error()Response.error() 都不允许自定义网络错误响应。MSW 选择遵守该行为,特别是因为自定义网络错误消息在不同的请求客户端之间处理不一致(有些会暴露错误,有些则不会)。

¥Note that neither HttpResponse.error() nor Response.error() allow customizing the network error response. MSW chooses to abide by that behavior, especially since the custom network error messages are handled inconsistently across different request clients (some expose the error, others do not).

自定义方法

¥Custom methods

HttpResponse 类还附带一组自定义静态方法来简化响应声明。这些方法在 Fetch API 规范中没有替代方案,并且完全是特定于库的。

¥The HttpResponse class also comes with a set of custom static methods to simplify response declaration. These methods do not have alternatives in the Fetch API specification and are entirely library-specific.

HttpResponse.text(body, init)

使用 Content-Type: text/plain 标头和给定的响应主体创建一个 Response 实例。

¥Creates a Response instance with the Content-Type: text/plain header and given response body.

HttpResponse.text('Hello world!')

HttpResponse.xml(body, init)

使用 Content-Type: application/xml 标头和给定的响应主体创建一个 Response 实例。

¥Creates a Response instance with the Content-Type: application/xml header and given response body.

HttpResponse.xml(`
<post>
  <id>abc-123</id>
  <title>Modern Testing Practices</title>
</post>
`)

HttpResponse.formData(body, init)

使用 Content-Type: multipart/form-data 标头和给定的响应主体创建一个 Response 实例。

¥Creates a Response instance with the Content-Type: multipart/form-data header and given response body.

const form = new FormData()
form.append('id', 'abc-123')
form.append('title', 'Modern Testing Practices')
 
HttpResponse.formData(form)

HttpResponse.arrayBuffer(body, init)

使用给定的 ArrayBuffer 主体创建一个新的 Response 实例。根据缓冲区的字节长度自动设置 Content-Length 响应标头。不设置任何额外的标头,如 Content-Type

¥Creates a new Response instance with the given ArrayBuffer body. Automatically sets the Content-Length response header based on the buffer’s byte length. Does not set any additional headers like Content-Type.

HttpResponse.arrayBuffer(buffer, {
  headers: {
    'Content-Type': 'application/octet-stream',
  },
})

相关材料

¥Related materials

Mocking responses

Learn about response resolvers and the different ways to respond to a request.