Close a WebSocket Client Connection with Mock Service Worker

Share this video with your friends

Social Share Links

Send Tweet

Let's see how our WebSocket client reacts to the connection being closed. Use the client.close() method in the event handler to reliably reproduce client connection closures.

Resources

[00:00] You can close the connection to any intercepted WebSocket client by calling client.close. You can see that in the UI we're getting this nice notification saying that the client has been disconnected. We can see this because in our root route we have this onClose handler that renders this toast message if we receive a close code that equals 1000, which stands for graceful WebSocket connection closures. But closing the client connection as soon as it actually connects is not very useful because it leaves our application non-interactable. So how about instead we close the client only when it sends a particular message in the chat.

[00:35] Let's head to handlers.ts and refactor this a little bit. I will remove this close call and in our message handler, let's remove this check here and instead use our parse chat message utility from earlier. So we will store the parse message in the variable called message. And if it's not a supported message, we will ignore it. But if it's a supported message, let's check the message data text to be close.

[01:01] And if it is, let's call client.close and stop the handling. So let's see what happens when I send the message close in the chat. See that the connection has been closed because MSW intercepted this outgoing client message, parsed it as a valid message, and saw that the text of that message was close, and then it called client.close() and prevented any further handling, so we never saw this message broadcasted in the UI.