拦截源
拦截并处理事件源。
你可以使用 sse 命名空间为其定义请求处理程序,从而在应用中拦截任何 EventSource 消息。例如,考虑以下事件源:
¥You can intercept any EventSource in your applicatio by defining a request handler for it using the sse namespace. For example, consider this event source:
new EventSource('https://api.example.com/events')通过 URL 拦截连接并开始处理连接:
¥Intercept it by its URL and start handling the connection:
import { sse } from 'msw'
export const handlers = [
sse('https://api.example.com/events', ({ request, client, server }) => {
client.send({ data: 'hello world' })
}),
]谓词
¥Predicate
服务器发送事件可以使用与 HTTP 请求 相同的谓词类型,包括:
¥You can use the same predicate types for Server-Sent Events as you would use for HTTP requests, which includes:
-
相对 URL;
¥Relative URLs;
-
绝对 URL;
¥Absolute URLs;
-
正则表达式。
¥Regular expressions.
例如,以下是如何拦截发送到远程服务器的 EventSource 事件,并传入动态路径段 id:
¥For example, here’s how you can intercept an EventSource to a remote server with a dynamic path segment id:
sse('https://api.example.com/events/:id', ({ params }) => {
console.log(params.id)
})响应解析器
¥Response resolver
sse 处理程序的响应解析器对象参数具有以下属性:
¥The following properties are available on the response resolver object argument for the sse handler:
| 属性 | 类型 | 描述 |
|---|---|---|
client | ServerSentEventClient | 已拦截 EventSource 客户端连接对象。 |
server | ServerSentEventServer | 实际的 EventSource 服务器连接对象。 |
request | Request | 获取拦截请求的 API 表示。 |
requestId | string | 代表被拦截请求的 UUID。 |
params | Record<string, string | string[]> | 请求 路径参数(例如 :userId)。 |
cookies | Record<string, string> | 已解析 请求 cookie。 |
相关材料
¥Related materials
与服务器发送事件 (Server-Sent Events) 使用 HTTP 类似,使用 sse 命名空间与使用 http 命名空间有很大的重叠。我们强烈建议你熟悉如何使用 MSW 拦截 HTTP 请求,因为这将解答你可能遇到的许多关于服务器发送事件的问题。
¥Much like Server-Sent Events utilize HTTP, working with the sse namespace has a significant overlap with the http namespace. We highly recommend getting yourself familiar with intercepting HTTP requests with MSW since that will answer a lot of questions you might have around Server-Sent Events.
Intercepting requests
Learn how to intercept outgoing requests.
后续步骤
¥Next steps
既然你已经了解如何拦截 EventSource 连接,现在是时候学习如何处理它们了(发送模拟事件、连接到真实服务器等)。
¥Now that you know how to intercept EventSource connections, it’s time to learn more about handling them (sending mock events, connecting to the real server, etc).
Server events
Mocking Server-Sent Events.