How to Wait for Element to Disappear in Cypress

How to Wait for Element to Disappear in Cypress

Ferenc Almasi β€’ 2021 October 03 β€’ Read time 2 min read
  • twitter
  • facebook

If you specifically need to wait for an element to disappear in Cypress, then you might want to use the wait command:

Copied to clipboard!
cy.wait(5000);
cy.get('.page').should('not.exist');

The code example above waits for 5 seconds before verifying the existence of an element on the page. However, you probably don't need to use cy.wait most of the time. Instead, you want to wait for the request or action to take place that the element you are trying to verify depends on.

Let's say that the element which supposes to disappear, does so when a request is finished. In this case, you can wait for the specific request to finish before verifying the presence of the element:

Copied to clipboard! Playground
cy.intercept('POST', '/remove').as('removePage');
cy.wait('@removePage').then(() => {
  // Work on the element that depends on the request
  cy.get('.page').should('not.be.visible');
  cy.get('.page').should('not.exist');
});

Another case could be that the visibility of the element directly depends on a user's action, such as clicking on a button. In this case, you can verify the presence of the element after triggering a click on the said button:

Copied to clipboard!
cy.get('.delete').click();
cy.get('.page').should('not.exist');

So when you want to use cy.wait, make sure you first ask yourself, do I really need to wait a predefined amount of time before doing a verification? Or does this depend on something else?

By using fixed timeouts with cy.wait, you not only increase the chance of random failures (what if it takes 6 seconds for an element to disappear instead of 5?), but you also increase the time it takes for your test suite to run by a fixed time.

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Wait for Element to Disappear in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.