Cypress on click, is there any method to wait until DOM is loaded? (without using wait())

Viewed 586

I have a small problem in React project, when I want to use .click() from Cypress sometimes I have an error failed because this element is detached from the dom. The simple solution is to add wait() before each test to let the site render fully but it isn't the best solution for me. Is there any way to do it without using wait()?

3 Answers

How about you write an should('be.visible') assertion before clicking the button. Something like:

cy.get('button').should('be.visible').click()

Cypress docs are your friend =)

I found this blog on docs. It details using cypress-pipe to have a callback function before the assertion

// create a click function as pipe does not take any cypress commands
const click = $el => $el.click()

cy.get('.your-element')
  .should('be.visible')
  .pipe(click)
  .should($el => {
    // whatever assertion you need after your click event is attached
  })

// calendar should close on the user click
cy.get('.owl-dt-popup').should('not.be.visible')

This is related to a known cypress issue that they promise to fix soon: https://github.com/cypress-io/cypress/issues/7306

Until that's solved you can either add .wait(), if it works for your scenario, or alternative try .click({force: true}). Either have downsides though.

Related