On a recent project, we started using Cypress to write our integration tests. When running the test suite, tests would fail randomly with timeout issues. In this tutorial, you will learn a few different ways to solve this problem. Sounds good, then read on.
Increase The Timeout Size
If you have a test that fails due to a timeout, one quick way to try and solve the problem is to increase the length of the requests timeout length. You can do this by passing in a second optional parameter when you make a
.visit() request, like so:
Increasing the timeout size is a bit of a hack and it's not the approach I would recommend to fix the test, but it can help.
A more strategic solution to solving the problem is to try and diagnose what is causing the timing out and trying to fix it. In my situation, a lot of the tests failed because third-party requests, like the calls to Google analytics, made the page load too long and it timed out.
To stop these requests from preventing your page to load, you can blacklist them. When you blacklist a host, when the test runs and the page loads, when it makes a request to a blacklisted host, Cypress will return 503 instead of making the request so the test can continue. To blacklist a host within Cypress, within your cypress.json file, add a 'blacklistHosts' option. This can be a single string, or, an array like this:
Now when you run the tests within the cypress test runner, you should now see your blacklisted request returning a 503.
Mocking A Request
Instead of applying a global blacklist, you can also mock requests on a per-test basis. Note, this only works for XHR requests so if you have a large image on your page then this will not work.
With these three techniques, you should be able to solve the majority of timeout issues you experience. If none of the above help and your pages are still timing out and making your tests fail, then I suggest you revisit your code, because I would hazard a guess you need to optimize your website.