Mocking Server-Sent Events
拦截并模拟服务器发送事件 (SSE)。
Mock Service Worker 附带一个一流的 API,用于通过库提供的 sse 命名空间拦截和模拟 服务器发送事件 (SSE):
¥Mock Service Worker ships with a first-class API for intercepting and mocking Server-Sent Events (SSE) via the sse namespace provided by the library:
import { sse } from 'msw'sse
API reference for the `sse` namespace.
与 http 的区别
¥Difference from http
服务器事件流仍然是一个常规的 HTTP 连接,这意味着你可以像处理任何其他 HTTP 请求一样,使用 http 命名空间进行拦截和模拟:
¥The stream of server events is still a regular HTTP connection, which means you can intercept and mock with the http namespace as you would any other HTTP request:
import { http } from 'msw'
export const handlers = [
http.get('/stream', ({ request }) => {
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('data: Hello World\n\n'))
controller.close()
},
})
return new Response(stream, {
headers: {
connection: 'keep-alive',
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
},
})
}),
]然而,通过 http 命名空间处理 SSE 存在一些缺点:
¥Handling SSE via the http namespace, however, has a number of disadvantages:
-
你必须手动构建流;
¥You have to manually construct the stream;
-
你必须对发送的消息进行编码,并确保其符合标准;
¥You have to encode sent messages and make sure they adhere to the standard;
相比之下,sse 命名空间为你提供了一种类型安全的、高级的 SSE 使用体验:
¥In comparison, the sse namespace provides you a type-safe, high-level experience of working with SSE:
import { sse } from 'msw'
export const handlers = [
sse<{ message: string }>('/stream', ({ client }) => {
client.send({ data: 'hello world' })
queueMicrotask(() => {
client.close()
})
}),
]通信的实现细节(例如流管理和消息排队)已被抽象化,使你能够专注于描述所需的网络行为。sse 命名空间还支持一些直接使用 EventSource 时无法实现的功能,例如转发名称不明确的原始服务器事件。
¥The implementation details of the comnunication, such as managing the stream and queuing messages, are abstracted away, allowing you to focus on describing the network behavior you want. The sse namespace also enables additional feature otherwise unavailable when working with EventSource directly, such as forwarding of the original server events with ambiguous names.
后续步骤
¥Next steps
以下各节将指导你了解拦截和模拟服务器发送事件 (Server-Sent Events) 的所有内容:
¥The following sections will guide you through everything you need to know about intercepting and mocking Server-Sent Events:
Intercepting sources
Intercepting and handling event sources.
Server events
Mocking Server-Sent Events.