建立服务器连接

WebSocket API 类似,你可以通过调用 server.connect() 来建立与服务器的实际连接:

¥Similar to the WebSocket API, you can establish an actual connection to the server by calling server.connect():

sse('/stream', ({ server }) => {
  const source = server.connect()
})

调用 server.connect() 的结果是一个 EventSource 实例,你可以使用它来监听和处理从实际生产服务器接收到的事件。

¥The result of calling server.connect() is an EventSource instance that you can use to listen and handle the events received from the actual production server.

事件转发

¥Event forwarding

默认情况下,所有服务器事件都会转发给客户端。这意味着调用 server.connect() 会将你的请求处理程序转换为透明代理。你可以使用它来检查传入的服务器流量并做出响应,例如,通过触发 WebSocket 事件。

¥By default, all server events are forwarded to the client. That means that calling server.connect() turns your request handler into a transparent proxy. You can use that to inspect the incoming server traffic and react to it, e.g. by emitting WebSocket events.

import { sse, ws } from 'msw'
 
const chat = ws.link('https://api.example.com/chat')
 
export const handlers = [
  chat.addEventListener('connection', () => {}),
 
  sse('/stream', ({ server }) => {
    const source = server.connect()
 
    source.addEventListener('message', (event) => {
      // If the actual server sends a certain event,
      // broadcast mock data on the WebSocket connection.
      if (event.data === 'hello') {
        chat.broadcast('Hello from the server!')
      }
    })
  }),
]

你可以通过在接收到的服务器事件上调用 event.preventDefault() 来选择退出默认的服务器到客户端事件转发。例如,以下是如何阻止包含特定有效负载的服务器事件,并向客户端发送另一个模拟有效负载:

¥You can opt-out from the default server-to-client event forwarding by calling event.preventDefault() on the received server event. For example, here’s how you can prevent a server event with a particular payload and send another, mocked payload to the client instead:

sse('/stream', ({ server, client }) => {
  const source = server.connect()
 
  source.addEventListener('message', (event) => {
    if (event.data === 'hello') {
      event.preventDefault()
      client.send({ data: 'Hello from the mock!' })
    }
  })
})

阻止默认设置会阻止所有事件的转发:openmessageerror

¥Preventing the default prevents the event forwarding for all events: open, message, and error.