How to Wait for Element to Disappear in Cypress
If you specifically need to wait for an element to disappear in Cypress, then you might want to use the wait
command:
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:
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:
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:
Resources:
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: