模拟响应
声明和使用模拟响应。
使用模拟响应来响应被拦截的请求是 MSW 最常见的用例之一。请注意,它是 并非处理请求的唯一方式。本页将概述如何创建模拟响应并在请求处理程序中使用它们。
¥Responding to an intercepted request with a mocked response is one of the most common use cases for MSW. Note that it isn’t the only way to handle a request. This page will give you an overview of how to create mocked responses and use them in your request handlers.
Fetch API 限制
¥Fetch API limitations
使用 MSW 时,你将使用 Fetch API Response
实例来描述模拟响应。依赖 Web 标准可以提供熟悉且灵活的模拟体验,重用现有的网络实用程序,并实现知识迁移。
¥When working with MSW, you will be using Fetch API Response
instances to describe mocked responses. Relying on a web standard allows for a familiar and flexible mocking experience, reusing of the existing network utilities, and transferable knowledge.
虽然你始终从服务器的角度编写模拟,但 Fetch API 并非设计用于声明服务器响应。该 API 包含一些限制,这些限制在客户端有意义,但在模拟中则不太有意义:
¥While you always write your mocks from the server’s perspective, the Fetch API isn’t designed to declare server responses. The API contains several restrictions that make sense on the client but less so in your mocks:
-
某些响应标头(例如
Set-Cookie
)是 forbidden;¥Some response headers, like
Set-Cookie
, are forbidden; -
禁止设置
2xx
-5xx
范围之外的状态码;¥Setting status codes outside of the
2xx
-5xx
range are forbidden;
使用 MSW 模拟响应时,这些限制均不适用。你可以模拟 cookies,设置其他不可配置的状态码(例如 101 Switching Protocols
),并像声明服务器响应一样声明模拟的响应。这是通过使用库提供的 HttpResponse
超集类来实现的。在声明模拟响应时,请优先使用它。
¥None of these restrictions apply when mocking responses with MSW. You can mock cookies, set otherwise non-configurable status codes, like 101 Switching Protocols
, and declare mocked responses as you would server responses. That is achieved by using the HttpResponse
superset class provided by the library. Please prefer using it when declaring mocked responses.
响应请求
¥Responding to requests
返回模拟响应
¥Return a mocked response
你可以通过构建所需的 Fetch API Response
实例并从响应解析器返回该实例,使用模拟响应来响应拦截的请求。
¥You can respond to an intercepted request with a mocked response by constructing the Fetch API Response
instance you want and returning it from the response resolver.
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get<never, never, string>('/resource', () => {
return HttpResponse.text('hello world')
}),
]
你也可以返回一个普通的 Fetch API
Response
实例。建议使用HttpResponse
类,它是Response
的直接替代品,但可以提升开发者体验,并解锁其他不可用的功能,例如模拟set-cookie
标头。¥You can return a plain Fetch API
Response
instance, too. It’s recommended to use theHttpResponse
class instead, which is a drop-in replacement forResponse
but provides improved developer experience and unlocks otherwise unavailable features, like mocking theset-cookie
header.
抛出模拟响应
¥Throw a mocked response
如果你在响应解析器中的任何位置抛出一个 Response
实例,该响应将被用作请求的模拟响应。这对于在请求处理过程中的任何地方短路解析器流程特别方便。
¥If you throw a Response
instance at any point in the response resolver, that response will be used as the mocked response for the request. This is particularly handy for short-circuiting the resolver flow anywhere during the request handling.
function withAuthorization(request: Request) {
if (!request.headers.get('authorization')) {
throw HttpResponse.text('Unauthorized', { status: 401 })
}
}
http.get<never, never, { id: string }>('/resource', ({ request }) => {
withAuthorization(request)
return HttpResponse.json({ id: 'abc-123' })
})
在此示例中,如果
GET /resource
请求不包含Authorization
标头,它将收到 “401 未授权” 响应。否则,它将继续处理模拟的 JSON 响应。¥In this example, the
GET /resource
request will get a “401 Unauthorized” response if it doesn’t contain theAuthorization
header. Otherwise, it will proceed with the mocked JSON response.
响应声明
¥Response declaration
强烈建议你熟悉 Fetch API Response
类。模拟各种响应场景最终都归结于使用该标准类进行声明。下面是一些常见示例。请务必探索左侧部分,了解更多高级用例。
¥It is highly recommended you get yourself familiar with Fetch API Response
class. Mocking various response scenarios will come down to declaring them using that standard class. Below, you can find a few common examples. Make sure to explore the section to your left for more advanced use cases.
状态码
¥Status code
http.get('/resource', () => {
return new HttpResponse(null, { status: 404 })
})
响应标头
¥Response headers
http.get('/resource', () => {
return HttpResponse.json(
{ id: 'abc-123' },
{
headers: {
'content-type': 'application/hal+json',
},
},
)
})
响应正文
¥Response body
你可以使用所有受支持的响应主体类型,例如字符串、Blob
、ArrayBuffer
、FormData
、URLSearchParams
和 ReadableStream
作为模拟响应的主体。
¥You can use all the supported response body types, like strings, Blob
, ArrayBuffer
, FormData
, URLSearchParams
, and ReadableStream
as the body of your mocked response.
http.get('/resource', () => {
return HttpResponse.text('hello world')
})
了解有关静态简写方法(例如
.text()
、.json()
以及HttpResponse
API 参考 中的其他方法)的更多信息。¥Learn more about the static shorthand methods like
.text()
,.json()
, and others in theHttpResponse
API reference.
后续步骤
¥Next steps
请探索 “模拟 HTTP” 部分,了解更多方案和高级模拟场景。以下是一些值得注意的参数:
¥Please explore the “Mocking HTTP” section for more recipes and advanced mocking scenarios. Here are a few noteworthy ones: