To wait for an element to disappear in Cypress, we typically use the .should('not.exist') assertion. This causes Cypress to retry the assertion until it passes, meaning the element no longer exists in the DOM. This is a highly practical feature, especially when handling asynchronous operations, such as waiting for a loading indicator to disappear before proceeding with subsequent steps.
For example, suppose you have a loading indicator that appears on the page during asynchronous operations and vanishes after the operation completes. The HTML element for the loading indicator might look like this:
html<div id="loading-indicator">Loading...</div>
When you want to wait for this loading indicator to disappear in your test, you can write Cypress code as follows:
javascript// Wait for the loading indicator to disappear cy.get('#loading-indicator').should('not.exist');
This code retrieves the element with the ID loading-indicator and asserts its non-existence. Cypress continuously retries this assertion until the default timeout (typically 4 seconds, but configurable) expires. If the element disappears within this window, the test proceeds. If it remains present beyond the timeout, the test fails.
Additionally, if you need to wait for an element to become invisible (i.e., it still exists in the DOM but is no longer visible), you can use the .should('not.be.visible') assertion.
For instance, if the loading indicator becomes invisible but persists in the DOM, you can implement this:
javascript// Wait for the loading indicator to be invisible cy.get('#loading-indicator').should('not.be.visible');
These two approaches enable you to manage element disappearance scenarios in Cypress tests, ensuring appropriate synchronization between assertions and operations.