Cypress interactions commands race condition

Viewed 238

When I try to, for example, click on a button using Cypress, the get command will get the button before it is actionable (still invisible for example). The click command later will fail because the subject passed to it is not actionable. How to avoid this behavior?

2 Answers

Try adding a visibility assertion

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

You can add visibility check as well as make sure the button is enabled and then perform a click().

cy.get('selector').should('be.visible').and('be.enabled').click()

I won't suggest you to overwrite an existing cypress command, instead create a custom command under cypress/support/commands.js like this:

Cypress.Commands.add('waitAndClick', (selector) => {
  cy.get(selector).should('be.visible').and('be.enabled').click()
})

And in your test you can add:

cy.waitAndClick('button')
Related