- Introduction
- Quick start
- Philosophy
- Comparison
- Default behaviors
- Limitations
- Debugging runbook
- FAQ
- Mocking HTTP
- Mocking GraphQL
- Mocking WebSocket
- Integrations
- API
- CLI
- Best practices
- Recipes
Client events
Intercepting and handling WebSocket client events
You can intercept the following WebSocket client events:
Event name | Description |
---|---|
message | Dispatched when the client is sending a message to the server. |
close | Dispatched when the client has closed the connection. |
The
open
event is represented by theconnection
event listener and doesn’t have a designated listener.
You can listen to these events by adding a respective event listener to the client
object anywhere in your event handler:
api.addEventListener('connection', ({ client }) => {
client.addEventListener('close', () => {})
})
Intercepting client events
The open
event
There is no open
event on the client
object. Instead, you should handle a client opening the connection in the connection
event listener:
api.addEventListener('connection', ({ client }) => {
console.log('Client opening connection', client)
})
The connection
event is dispatched on the WebSocket link whenever a client opens a new connection in your app. The listener is called before the actual client dispatches the open
event so you can forcefully close the connection without opening it.
If you don’t establish the actual server connection in the connection
listener, MSW will treat this connection as mocked and your handler will act as a server. If you choose to establish the actual server connection, the open
and other client events will be dispatched based on that connection’s state.
The message
event
You can intercept the data sent from your client by adding a message
listener on the client
object:
api.addEventListener('connection', ({ client }) => {
client.addEventListener('message', (event) => {
console.log('Intercepted message from the client', event)
})
})
The
event
argument of themessage
listener is aMessageEvent
instance. You can read the data sent from the client via theevent.data
property.
Your mocks are always written from the server’s perspective, which means the message
event will be dispatched when your client sends some data:
// app.js
const ws = new WebSocket(url)
ws.onopen = () => {
ws.send('hello world')
// "Client sent data: hello world"
}
The close
event
You can intercept the close
event dispatched when your client closes the connection by adding a close
event listener on the client
object:
api.addEventListener('connection', ({ client }) => {
client.addEventListener('close', (event) => {
console.log('Client is closing the connection', client)
})
})
The
event
argument of theclose
listener is aCloseEvent
instance. It contains additional information about the closure, like theevent.code
andevent.reason
.