In this tutorial, you will learn how to create more stable Cypress tests. Writing tests for some parts of your application can be tricky. There are loads of reasons why a test can fail, one of the most annoying reasons are async
issues. Trying to figure out why a test times out on some occasions but runs on others can be painful. One reason why a Cypress test can timeout is down to the application. The first request to an application will often take longer than a second request. The speed at which some elements on your page load might be outside of your control, for example, the length of time an external API call takes to return data. In a perfect world, we would fix the application to load instantly whenever it is called. In real life, we will not have that luxury. When writing Cypress tests we need a strategy for dealing with pages that take a little while to load. In this tutorial, you will learn how to do that.
Cypress Plugin Retries
The first obvious choice is to simply configure Cypress to have a longer default timeout. This solution is not ideal. In most instances, you will only have one or two problem areas in your codebase that take a little while to load. Extending the timeout for all tests is unnecessary. If you find yourself in this situation then this is where Cypress Plugin Retries comes in. This package can be run globally or on a per-test level which is ideal! This package can be installed using this command:
Within cypress/support/index.js
you need to add this line:
After the plug-in has been installed, the next step is to enable it in your project. There are several ways to do this. First, you can add the CYPRESS_RETRIES
command within your package.json
test script. Add this to the command that you use to launch cypress:
The important part of this script is this part, CYPRESS_RETRIES=3
. Now when you run your Cypress project, before the build is failed from a single timeout, Cypress will try and run the test 3 times. Granted this approach feels a bit hacky, but it has helped me out a lot in the last few months. A second approach to configure the package globally is to set the env
key in cypress.json
, like this:
If you decide you want to retry on a per-test basis, you can run this code:
Update 08/25/20: Test retries has made it to Cypress core! The advice in this tutorial will apply to Cypress v5.0.0 without the need for installing the package!
Happy Coding!