Broadcast a Mocked Message to All WebSocket Clients

Letting you know about the WebSocket connections isn't the only thing a WebSocket link can do. In fact, it also gives you a broadcast() method to send a message to all the connected clients. Let's use that to broadcast a chat message in our app across multiple open browser tabs.

Resources

Share with a coworker

Transcript

[00:00] Here, I have multiple people using our chat application, but when one of them sends a message, the other one can't see that message at all. That is happening because MSW sends the confirmation only to the particular client that issued that message. That can be handy if you want to communicate with an exact client in your mocks. But in this case, it's not enough. To send the data to all the connected clients, replace client.send with chat.broadcast.

[00:29] Notice that we're referencing this chat object, the WebSocketLink that we created earlier, and its broadcast method. This method will send the given data to all the connected WebSocket clients. And with these changes, both our users can exchange messages in the chat and actually see each other's messages.