In Cypress, waiting for an element to disappear can be achieved in multiple ways. The most common approach is to use the .should() assertion with not.exist or not.be.visible to wait for the element to vanish from the DOM or no longer be visible. Here are examples of several methods:
Using should('not.exist')
If you want to wait for an element to completely disappear from the DOM, you can do the following:
javascriptcy.get('.some-element').should('not.exist');
This instructs Cypress to wait until the element with the .some-element class no longer exists on the page.
Using should('not.be.visible')
If the element remains in the DOM but you want it to be invisible (e.g., hidden via CSS), you can use:
javascriptcy.get('.some-element').should('not.be.visible');
This tells Cypress to wait until the .some-element is no longer visible to the user.
Using wait combined with should
In scenarios where backend operations take time and cause the element to disappear, you may need to combine wait and should commands:
javascriptcy.wait('@yourApiCall'); cy.get('.some-element').should('not.exist');
Here, cy.wait('@yourApiCall') waits for an API call aliased as yourApiCall to complete. After completion, Cypress continues to wait for the .some-element to disappear.
Notes
-
Ensure your selectors are specific and unique. If the selector is not unique (e.g., multiple elements share the same class on the page), Cypress might identify other elements instead of the one you intend to wait for to disappear.
-
If your application uses animations, consider increasing the timeout duration, as the element's disappearance may not be immediate:
javascript
cy.get('.animated-element').should('not.be.visible', { timeout: 10000 });
shellThis extends the Cypress timeout for the element to become invisible to 10 seconds. By employing these methods, you can instruct Cypress to wait for an element to disappear, which is a common requirement in automated testing, especially when working with web applications that have asynchronous behavior.