How to wait for elements to disappear in cypress and JavaScript?

Estimated read time 2 min read

In Cypress, you can use the should('not.exist') command to wait for an element to disappear from the DOM. Here’s an example:

cy.get('#my-element').should('not.exist');

In this example, Cypress will wait until the element with the ID of my-element is no longer in the DOM before moving on to the next command. If the element never disappears, the test will eventually time out and fail.

If you need to wait for multiple elements to disappear, you can use the should('not.exist') command on each element in turn, or you can use the waitUntil() command with a custom callback function. Here’s an example of how to use waitUntil():

cy.waitUntil(() =>
  cy.get('.loading-spinner').should('not.exist')
);

In this example, Cypress will wait until all elements with the class loading-spinner have disappeared from the DOM before moving on to the next command. The waitUntil() command will retry the callback function until it either succeeds or times out.

Note that you should always try to avoid using cy.wait() or other hard-coded delays in your Cypress tests, as they can make your tests flaky and unreliable. Instead, use the built-in Cypress commands to wait for elements to appear or disappear before moving on to the next step in your test.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply