自定义事件
模拟自定义服务器事件。
你可以通过在客户端消息上提供 event 键来指定自定义事件类型:
¥You can specify the custom event type by providing the event key on the client message:
import { sse } from 'msw'
export const handlers = [
sse('/stream', ({ client }) => {
client.send({
event: 'greeting',
data: 'hello world',
})
}),
]这将导致客户端收到以下消息:
¥This will result in the following message received by the client:
event:greeting
data:hello world
自定义事件 ID
¥Custom event ID
你可以通过在发送的事件旁边提供 id 属性,将 自定义 ID 字段 附加到已发送的自定义事件:
¥You can attach a custom ID field to the sent custom event by providing the id property alongside the sent event:
client.send({
id: '1',
event: 'greeting',
data: 'hello world',
})id:1
event:greeting
data:hello world
TypeScript
你可以通过向 sse 函数提供一个类型参数对象,并在该对象中包含事件名称作为键,来为自定义事件的数据类型添加注释:
¥You can annotate the data type of your custom events by providing a type argument object to the sse function and including the event names as keys on that object:
sse<{ greeting: 'hello world' }>('/stream', ({ client }) => {
client.send({ greeting: 'hello world' }) // ✅
client.send({ greeting: 'goodbye cosmos' }) // ❌
})请注意,
message键保留给默认消息数据类型。你可以将默认的message数据类型和自定义事件组合在同一类型中。¥Note that the
messagekey is reserved for the default message data type. You can combine both the defaultmessagedata type and custom events within the same type.