服务器事件

模拟对象必须与实际使用情况相似。这是 MSW 中设计 API 的核心理念。虽然服务器发送事件是通过 EventSource 标准 API 使用的,但目前还没有从服务器定义此类事件的标准方法。因此,MSW 设计了一个自定义 API,该 API 既符合标准,又提供了一种类型安全且符合人机工程学的方式来处理服务器发送的事件。

¥Mocks must resemble actual usage. That is a core philosophy when it comes to designing APIs in MSW. While Server-Sent Events are consumed via the EventSource standard API, there is no standard way of defining such events from the server. Because of that, MSW takes the liberty of designing a custom API that remains standard-based while providing a type-safe and ergonomic way of working with Server-Sent Events.

事件对象

¥Event object

服务器事件是一个如下格式的对象:

¥A server event is an object of the following shape:

属性类型描述
idstring(可选)自定义事件 ID。
datastring事件有效负载。
eventstring(可选)自定义事件名称。
retrynumber(可选)重连时间。

发送事件

¥Sending events

要发送模拟的服务器发送事件,请调用 client.send() 并向其提供 事件对象

¥To send a mock server-sent event, call client.send() and provide it with the event object:

sse('/stream', ({ client }) => {
  client.send({ data: 'hello world' })
})

创建此请求处理程序会将 “Hello World” 事件发送到与处理程序谓词 (/stream) 匹配的 EventSource

¥Creating this request handler will send the “hello world” event to the EventSource matching the handler’s predicate (/stream):

// your-app.ts
const source = new EventSource('/stream')
event.addEventListener('message', (event) => {
  console.log(event.data) // "hello world"
})

后续步骤

¥Next steps

在以下页面中探索 sse API 的功能:

¥Explore what you can do with the sse API on the following pages:

Message events

Mocking server message events.

Custom events

Mocking custom server events.

Retry

Mocking the reconnection time.