Prevent WebSocket Event Propagation Between Listeners with MSW

Mocking WebSocket APIs resembles how you use them in the actual code. This means that you can control the event flow for your client and server events as you normally would when using EventTarget. Let's explore how to use event.stopPropagation() and event.stopImmediatePropagation() to achieve behavior layering when mocking WebSocket events.

Resources

Share with a coworker

Social Share Links

Transcript

[00:00] Much like the WebSocket communication, the way you handle it with MSW is also event-based. Understanding how those events flow through your handlers and different listeners you attach is crucial to achieving the behavior you want. For example, here I have two connection listeners for the same WAPT socket link. And because unlike HTTP handling, there is no really a state of a WAPT socket connection being handled. So I will see both of these console.log statements printed right here in the console representing these connection listeners.

[00:31] The same is true for other event listeners. For example, I can add a message event listener on the client. In fact, let's add multiple of these, labeling them message 1, 2, also another listener in the different connection handler here. Message 3. And once I send message on our WebSocket client, I will see both message 1, 2, and 3 being printed representing these different message listeners on the client, even if they belong to different connections.

[00:59] So by default, the event handling nature in MSW is accumulative. All the events happen at the same time across all your listeners. That can be handy if you want to layer different behaviors on top of each other. But sometimes you want to opt out of that layering. You can do so by using the standard API to prevent event propagation in JavaScript.

[01:19] For example, if I head to this first message listener I can call event.stopPropagation. Now when the client sends the message I will see message 1 and 2 being printed because they belong here to the same connection listener, but message 3 will be ignored because it belongs to a different connection listener. In other words, I've excluded that client message event from being handled by any connection listeners by the one that's declared over here. But I can also prevent the same message event from propagating to a sibling client message listener by calling eventStopImmediatePropagation. Now if the client sends the message, it will only call the first message listener over here, ignoring the sibling listener because I've called stop immediate propagation.

[02:08] Take advantage of the layered event handling in MSW but also keep in mind that you can opt out from it by using event stop propagation and event stop immediate propagation to short-circuit the events. And don't forget that you can also do that conditionally, for example, based on the payload sent in the event.