消息事件

模拟服务器消息事件。

你可以通过调用 client.send() 并提供消息数据来向客户端发送模拟消息事件:

¥You can send a mock message event to the client by calling client.send() and providing it with the message data:

import { sse } from 'msw'
 
export const handlers = [
  sse('/stream', ({ client }) => {
    client.send({ data: 'hello world' })
  }),
]

显式提供 event: 'message' 属性无效,相当于完全不提供 event 属性。

¥Providing an explicit event: 'message' has no effect and is equivalent to not providing the event property at all.

这将导致客户端收到以下消息:

¥This will result in the following message received by the client:

data:hello world

有效负载

¥Payload

你可以将任何可序列化的有效负载作为消息数据发送。例如,你可以发送 JSON:

¥You can send any serializable payload as the message data. For example, you can send a JSON:

client.send({
  data: {
    user: {
      id: 'abc-123',
      name: 'John',
    },
  },
})

自定义事件 ID

¥Custom event ID

你可以通过在发送的事件旁边提供 id 属性,将 自定义 ID 字段 附加到已发送的消息事件:

¥You can attach a custom ID field to the sent message event by providing the id property alongside the sent event:

client.send({
  id: '1',
  data: 'hello world',
})
id:1
data:hello world

注意:事件 ID 必须是字符串。

¥Note: event ID must be a string.

TypeScript

你可以通过向 sse 函数提供一个类型参数对象,并在其中包含 message 键,来为消息事件的数据类型添加注释:

¥You can annotate the data type of the message event by providing a type argument object to the sse function and including the message key in it:

sse<{ message: 'hello world' }>('/stream', ({ client }) => {
  client.send({ data: 'hello world' }) // ✅
  client.send({ data: 'goodbye cosmos' }) // ❌
})