Let's add some realism to our mocks. We can get the server
object from the connection
listener arguments and establish a connection to the actual WebSocket server by calling server.connect()
. Once we do that, our event handler becomes a proxy sitting in-between our client and the actual server.
[00:00] Let's talk about how you can use MSW when you already have the actual WebSocket server. So here I've updated my client to reference a different URL that points to the WebSocket server I have running locally. Respectively, in handlers.ts I've updated the WebSocket link to point to a different URL as well so it would match that connection. And I've also removed any handling for that connection because I want the client events to be handled by the original server. But if I go to the chat and try to send something, I will see that nothing is happening.
[00:30] That is because by default MSW prevents the actual WebSocket server connections from being established. This is really handy when you want to develop mock first or test your application. But let's see how to change that. To establish the actual WebSocket connection, head to the connection listener and in the argument, access the server object. Similar to how the client object allowed you to control the particular intercepted WebSocket client, the server object gives you control over the actual server connection.
[00:57] So to establish this connection, call server.connect. Now if you head to the browser and open the DevTools and the Network tab you can see that there's an actual WebSocket connection established to the provided URL and you can see the messages here once we're going to send them in the chat. For example, hi, we will see the outgoing message and also the incoming message from the server.