mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.97k stars 519 forks source link

feat: support server-sent events #2299

Open kettanaito opened 1 month ago

kettanaito commented 1 month ago

Todo

References

kettanaito commented 1 month ago

Augmenting actual server-sent events

sse(url, ({ source, server }) => {
  // This creates a new EventSource request
  // and propagates all the events from here
  // to the underlying pending stream for `source`.
  server.connect()
})

Modifying the event is similar to that in WebSockets: prevent its default and send a new event:

sse(url, ({ source, server }) => {
  server.connect()

  server.addEventListener('message', (event) => {
    // Prevent this server event from reaching the client.
    event.preventDefault()
    const newEvent = modify(event.data)
    source.send(newEvent)
  })
})

May be a good idea to rename source to client and have a consistent SSE/WebSocket experience.

kettanaito commented 1 month ago

The tests are failing likely due to Node.js bump to v20 in CI.

Edit: Looks like an issue specific to a particular version of Node.js. Reported here: https://github.com/nodejs/undici/issues/3676