How to wait for element to disappear in cypress

jaikl picture jaikl · Dec 7, 2018 · Viewed 29.5k times · Source

I have a loading indicator that i need to wait for to disappear before doing my assertions.

I´ve seen some use the following, but it does not seem work for me and also i don´t want it to be an assertion. cy.get('element, {timeout: 10000}).should('not.exist);

Anyone having any tips?

Answer

Diogo Rocha picture Diogo Rocha · Dec 7, 2018

If you specifically need to wait, you could use the wait() function of cypress before making an assertion, and provide the amount of time to wait before timeout.

But note, this is an anti-pattern as you can find in the docs:

You almost never need to wait for an arbitrary period of time. There are always better ways to express this in Cypress.

That said, if your loading indicator is bound to some network request, you can wait for them to finish before making an assertion. This could be achieved with something like this example:

// Wait for the route aliased as 'getAccount' to respond
// without changing or stubbing its response
cy.server()
cy.route('/accounts/*').as('getAccount')
cy.visit('/accounts/123')
cy.wait('@getAccount').then((xhr) => {
  // we can now access the low level xhr
  // that contains the request body,
  // response body, status, etc
})

More info about waiting for requests could be found here.

Also, make sure that you really want to use .should('not.exist') and not .should('not.be.visible').