Use a Custom Close Code to Close a WebSocket Connection with MSW

With MSW, you can use custom close codes that are otherwise unusable on the client. For example, in this lesson we will emulate a WebSocket connection closure due to a 1003 status code, which means that the server is unable to process the incoming data.

Resource

Share with a coworker

Transcript

[00:00] Calling client.close() without any arguments stands for a graceful connection closure, the one that has 1000 as the close code. This is the only way to close a WebSocket connection on the client, but when writing handlers with MSW, we are describing the server, not the client. This means that we can pass a custom close code as the argument to client.close. For example, I can pass a 1003 as the close code, which stands for a connection error when the server is unable to process the data sent from the client. If I save this and type the close message again, I can see a connection error pop-up right here, also displaying the right close code, 1003.

[00:42] This is extremely powerful because client.close allows you to emulate different closure scenarios from the server, the ones you cannot otherwise reproduce on the client alone.