- Introduction
- Quick start
- Philosophy
- Comparison
- Default behaviors
- Limitations
- Debugging runbook
- FAQ
- Mocking HTTP
- Mocking SSE
- Mocking GraphQL
- Mocking WebSocket
- Integrations
- API
- CLI
- Best practices
- Recipes
Intercepting sources
Intercepting and handling event sources.
You can intercept any EventSource in your applicatio by defining a request handler for it using the sse namespace. For example, consider this event source:
new EventSource('https://api.example.com/events')Intercept it by its URL and start handling the connection:
import { sse } from 'msw'
export const handlers = [
sse('https://api.example.com/events', ({ request, client, server }) => {
client.send({ data: 'hello world' })
}),
]Predicate
You can use the same predicate types for Server-Sent Events as you would use for HTTP requests, which includes:
- Relative URLs;
- Absolute URLs;
- Regular expressions.
For example, here’s how you can intercept an EventSource to a remote server with a dynamic path segment id:
sse('https://api.example.com/events/:id', ({ params }) => {
console.log(params.id)
})Response resolver
The following properties are available on the response resolver object argument for the sse handler:
| Property | Type | Description |
|---|---|---|
client | ServerSentEventClient | Intercepted EventSource client connection object. |
server | ServerSentEventServer | Actual EventSource server connection object. |
request | Request | Fetch API representation of the intercepted request. |
requestId | string | UUID representing the intercepted request. |
params | Record<string, string | string[]> | Request path parameters (e.g. :userId). |
cookies | Record<string, string> | Parsed request cookies. |
Related materials
Much like Server-Sent Events utilize HTTP, working with the sse namespace has a significant overlap with the http namespace. We highly recommend getting yourself familiar with intercepting HTTP requests with MSW since that will answer a lot of questions you might have around Server-Sent Events.
Intercepting requests
Learn how to intercept outgoing requests.
Next steps
Now that you know how to intercept EventSource connections, it’s time to learn more about handling them (sending mock events, connecting to the real server, etc).
Server events
Mocking Server-Sent Events.