Send Mocked WebSocket Client Messages to the Original Server with MSW

Share this video with your friends

Social Share Links

Send Tweet

The WebSocket client events are also being forwarded to the original WebSocket server since we've called server.connect(). Luckily, to opt-out from this forwarding we have to do just the same—call event.preventDefault() on any client event we don't want to be forwarded to the server.

Resources

[00:00] We can also prevent the default message forwarding from the client to the server in a similar way. This can come in handy if you want to modify the message sent from the client before it reaches the server. To do that, let's call client, add event listener, add the message event listener, and grab the event. Now call event prevent default to prevent this message forwarding. So now all the events that our client sends will never reach the server.

[00:27] They will short circuit on the MSW level. We can introduce the same message parsing, I will copy it from here. And now let's modify the message by changing the author's name to be MSW. Now to send this modify message to the server, call server.send() and provide it with a new message. Let's use the create chat message utility and pass the modified message right here.

[00:50] Now sending messages in the chat will replace its author to be MSW, exactly what was specified here in the modified message, because that is the only message that the actual server receives.