- Introduction
- Quick start
- Philosophy
- Comparison
- Default behaviors
- Limitations
- Debugging runbook
- FAQ
- Mocking HTTP
- Mocking GraphQL
- Mocking WebSocket
- Integrations
- API
- CLI
- Best practices
- Recipes
Establishing server connection
By default, MSW does not establish a WebSocket connection to the actual server. You can, however, establish such a connection at any point in your event handler by calling server.connect()
.
const api = ws.link('wss://api.example.com')
export const handlers = [
api.addEventListener('connection', ({ server }) => {
server.connect()
}),
]
In the example above, server.connect()
will establish a new, bypassed WebSocket connection to the underlying WebSocket URL ('wss://api.example.com'
).
Just like establishing connections with new WebSocket()
, you do not have
to await the server.connect()
call.
API reference
server.connect()
The `server.connect()` API reference.
Managing the connection
Once you establish the connection, the server
object becomes your point of entry to managing the said connection. For example, you can listen to the original connection erroring by adding an error
listener to the server
object:
server.connect()
server.addEventListener('error', (event) => {
// Handle the original connection error.
})
Explore the “Server events” section to learn more about all the ways to manage server connections.
Event forwarding
Bear in mind that once the original server connection has been established, all the server events will be forwarded to the client, and all the client events will be forwarded to the original server. Learn how to manage that forwarding:
Server-to-client forwarding
Manage the server event forwarding.
Client-to-server forwarding
Manage the client event forwarding.