Test WebSockets in Playwright with MSW

Let's write an end-to-end test for our chat application using Playwright. For this one, we will reuse the browser integration of Mock Service Worker to also run during the automated test.

Resources

Share with a coworker

Transcript

[00:00] Here's how we can end-to-end test our chat application using Playwright. First, we have Playwright installed and configured. I'm using this basic configuration and provide the base URL so it's easier to navigate our application in tests and also spawn our application before the tests run using the web server command. Then to enable MSW during the playwright tests, I'm not doing anything extra, I'm still relying on our enable mocking function, basically the browser setup for MSW that we used to develop the chat application before. And finally in handlers.ts what I did I moved this happy path connection handler from my integration tests in Vitas to here so both the end-to-end and integration tests can reuse the same behavior.

[00:44] With this setup in place let's write first end-to-end test. I will add one in the end-to-end directory and call it chat.test.yes. Our end-to-end test will consist of three steps. First, sign in as a random user. Second, send the message.

[01:08] And third, assert the message in the UI. So I will visit the application by calling page go to slash and do the signing part. I'll click on the randomize button then on the join chat button and finally wait for the logout button to be visible indicating that the user has successfully logged in. Then I will send the message in the chat by locating the chat message input and typing hello world and after that clicking on the button that says send which should send the message event to the WAP socket server which in the case of our end-to-end test will be MSW. And finally to assert that the message is in the UI, I will grab the log element and also make sure that it has the hello world content, which is the content of the message that we're sending.

[01:56] Now we can run our end-to-end test using npm test end-to-end. This is a command I added to package.json, you can use whatever command you want. Effectively, this will run PlayWrite test. I can see the test passing, but let's also verify it by running PlayWrite in the UI mode. The UI mode will show us every step of the test as it's being run.

[02:18] So here I click to run all tests and wait for them to complete. Now that the test is also passing I can go through every individual step like this signing step or then typing the message and sending it, and also the message appearing in the UI over here. Meanwhile, behind the scenes, this test, our application in general, communicates with MSW instead of the actual server, taking the behavior in handlers.ts as the source of truth.