DEV Community

Milan Nicic
Milan Nicic

Posted on

Optimizing Your Cypress Tests: Tips for Efficient Waiting and Assertion Handling

Since I started writing automated tests I always looked for a best practices in terms of waiting. So lets start with basics, we all know there are implicit and explicit waits.

Lets start with implicit wait, for implicit wait in Cypress we have cy.wait() command in which we pass how much miliseconds we want to wait. This is bad approach and if you ask why? Here is the answer, for example if you want some element to appear and sometimes it appears in 2 seconds, sometimes in 3 seconds, sometimes in 5 seconds, you would need to put cy.wait(5000) in order to cover the latest time in which element can appear, but if element appears in 2 seconds, you will still wait 5 seconds no matter what happens. This is why this is a bad approach.

Instead we need to use explicit waits, in Cypress we have multiple options on how to use explicit waits I will count every wait that I use regularly in my tests!

First of all, the one that you will use the most is .should() command that waits for specific state for example this command in photo below will wait for element to be visible and then it will continue the test. Should command will constantly retry to see if element is visible by default 4 seconds, but we can change that in defaultCommandTimeout. This is a good practice!

ShouldBeVisible

There is another way to check is element is visible. I am using Cypress helper methods in this link there are all helper methods you can use! Particularly for this scenario I use Cypress.Dom.IsVisible as on photo below. Keep in mind this does exactly the same like in previous image, just another way. I added this just to let you know of different helper methods!

Cypress.dom.IsVisible

Keep in mind that .click() command in Cypress has built-in retry-ability to find and click on element, so if you have element that appears after few seconds, you don't need to use .should() assertion before actually clicking on element.

Click retry

Click finished

Another type of wait that we can use in Cypress is to wait some API request to finish before proceeding with the test. We can do this by using cy.intercept() command as on photo below

Intercept

Inside Cypress Runner

cy.wait() will resolve as soon as request is finished.

At the end of this post I want to go back to .should() command, what I want to mention is that with this command you can wait for almost anything, e.g. if list is loading slowly and you want to wait till list has length of 5 you can do that as on photo below

Should waiting for almost anything

These are explicit waits that I constantly use in my tests, I hope you found this blog useful for your daily work! If you did, please leave a follow on LinkedIn

See you in next blog!
Cheers!

Top comments (0)