Intercept a WebSocket connection with Mock Service Worker

Share this video with your friends

Social Share Links

Send Tweet

To intercept any WebSocket connection in your app, create a WebSocket link using the ws.link() API from MSW. Provide it a URL predicate and store the link in a variable. Then, add the connection event listener to your WebSocket link to know when a connection is being established. Provide the result of that event listener to your handlers array, and you're good to go!

Resources

[00:00] To intercept a WebSocket connection, go to handlers.ts and import ws-prom-msw. The ws namespace stands for WebSocket and contains all sorts of useful utilities for you to intercept and handle WebSocket connections. Now call ws.link() to create a WebSocket link. This method accepts a URL, which is a WebSocket connection URL. Our application makes a connection to this made-up example.com slash chat WebSocket URL.

[00:32] I will copy it and use it here for my WebSocket link. Creating this link returns you an object that you can use to listen to this connection being established in your app and also handle incoming and outgoing events. It's a good idea to name this object appropriately based on the service you're mocking. In our case, it's the chat service. Now head to the handlers array and add a connection listener on the chat by calling chat.connectionListener, providing connection as the event name and a second argument being a function which is a listener.

[01:05] When the connection event is dispatched I will print to the console saying new connection. Now if we head to our app in the browser and open the DevTools we can see this new connection string being printed and also MSW printing this message letting us know that it intercepted a WebSocket connection to example.com.chat. What's happening here is our application establishes connection to this WebSocket URL. MSW intercepts that connection and tries to see if there are any WebSocket links matching that URL. It finds our chat link and dispatches the connection event, calling our listener and printing this message to the console.