admin管理员组

文章数量:1335138

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?

Share Improve this question edited Jun 25, 2021 at 0:27 Connor Low 7,2363 gold badges37 silver badges63 bronze badges asked Jun 24, 2021 at 7:56 Raziel ZoharRaziel Zohar 1492 silver badges14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

The , for OR condition will not work if firstElement loads asynchronously.

Using the mand

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 mand 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

May be too late but might help someone looking for the solution -

This can be achieved using the :is Pseudo-class The :is pseudo-class allows you to bine multiple selectors:

cy.get(':is(selector1, selector2)')

You can use the ma , to do an OR condition if you are using css selectors. Something like:

cy.get('firstElement,secondElement').click()

本文标签: javascriptCypress how to use 39cyget39 between two elementsStack Overflow