Intercept WebSocket Client Events with Mock Service Worker

Share this video with your friends

Social Share Links

Send Tweet

The connection event listener of your WebSocket link exposes a bunch of useful parameters to you. One of those parameters is the client object that represents the intercepted WebSocket client that establishes the connection.

Add a message event listener on that client to know when it sends any messages in your application. And yes, this is a regular event listener! This means you get a MessageEvent instance as a parameter, and can observe the data sent via WebSocket.

Resources

[00:00] When a user sends a message in the chat, our application handles it by sending this stringified payload to the WebSocket server. This payload represents the message, with its type, and data like the author of the message, the text, and a bunch of other things. If I try sending a message right now by typing hello and submitting this, I will see that the MSW prints this log over here about an outgoing event being sent, and it provides the reference to the exact message event that's been sent and its stringified payload. But there's nothing happening in the UI, because our application expects a confirmation from the server that it has received a message. Let's fix that.

[00:41] Go to the handlers.ts file and to our connection listener over here. In the argument to this listener, spread an object and access the client property. This property, this object, represents an intercepted WebSocket client. Now in the listener, call client addEventListener and attach a listener to the message event. The message listener receives a message event instance as an argument.

[01:08] So let's console.log that event. Now when I try to send the same message I will see the MSW log over here, but also the log from our connection listener right here, containing the message event that's being sent. To send data back to the client, let's head to the listener for this message and call client.send. You can send all sorts of things over the WebSocket protocol, like strings, blobs, and buffers. Our application expects to receive the message event from the server, confirming that it has received it.

[01:41] So let's forward it as is, by providing event.data to the client.send() method. Once I do that, and try sending a message again, I will see it appearing in the UI because now I can see in addition to this outgoing message, MSW notifies me that the client receives the mock incoming message and then handles it by rendering this message for our user.