HomeNews & InsightsSimulating WebSocket events in Cypress

Simulating WebSocket events in Cypress

By Matthew Lowry 8th Dec 2022

There is no way around it. Being able to perform end-to-end testing of WebSockets can be very challenging, and we have seen some very complex solutions.

In this article, learn how we utilise Cypress to remove a lot of that complexity, isolate our front end and get repeatable, dependable events to verify behaviour from inside our automated tests.

One of the biggest challenges with testing WebSockets is testing behaviour after the state change.

Something we believe in at ClearRoute is having data-agnostic tests. That means no relying on a known snapshot, long living fixtures, or side effects to create the data the tests depend on.

Although occasionally a strategic short term win, teams will often find it becomes exponentially more challenging to understand what test data belongs to which test and almost impossible to change long-living fixtures due to unknowing the tests which are depending on the data.

In our opinion, a much nicer long term approach is for the automated tests to create all data the test depends upon each execution, so when a new breaking change gets introduced, the tests will ensure you update the test code and fixtures at the time of the change.

This concept is very relevant and can be applied in the events testing space. If an event gets changed or even misspelt, it’s often not an easy task to debug what the expected behaviour should be if you are solely relying on black box, end-to-end testing.

How powerful would it be if from inside a test you could simulate a publisher’s event or catch an event sent from the front end after an action occurs?

So let’s break it down, in the above code block you can see an example where we use Cypress to override and initialise a new WebSocket() on the window object directly form inside our test.


Top Tip:if you define and export your web socket messages your application code and test code can share the list of messages and it will will go a long way to reduce test maintenance by shifting the responsibility onto the application code!

Once initialised, all messages sent from the front end can be intercepted and asserted against, and our Cypress tests can simulate provider messages and verify the correct behaviour has occurred on the client.

By adopting this pattern teams can expect to benefit from faster and more accurate feedback by removing the requirement for the provider to interact with.

For teams with even more appetite for faster feedback, you could combine the above with our favourite Cypress pattern where we leverage Storybook to isolate single page application components and pages and test independently.

If you’re interested in learning more about our technical solutions to testing problems please get in contact with the team.