I want to search for an element and if I don't find it, find a second element:
cy.get(@firstElement).or(@secondElement).click()
Is there some function I can use like ||
in conditions?
I want to search for an element and if I don't find it, find a second element:
cy.get(@firstElement).or(@secondElement).click()
Is there some function I can use like ||
in conditions?
The ,
for OR condition will not work if firstElement
loads asynchronously.
Using the command
cy.get('firstElement, secondElement') // no retry on firstElement
It goes straight to secondElement
even if firstElement
appears just 10ms later, or is animating.
So this technique skips the Cypress retry mechanism, which is why Cypress does not mention it in the docs.
One way I can see to make it work when firstElement
is asynchronous is to catch the fail event.
Note
Cypress docs say to only use the fail event for debugging, but Cypress do use it in their own tests.
Cypress.once('fail', () => { // "once" means catch fail for next command only
console.log('Clicking secondElement')
Cypress.$('secondElement').trigger('click')
})
cy.get('firstElement', { log: false }) // retry for 'firstElement' but suppress log
.click() // never executes this if 'firstElement' fails
You can use the comma ,
to do an OR condition if you are using css selectors. Something like:
cy.get('firstElement,secondElement').click()