Reputation: 299
I am having a problem with if element exist then do something. As an example:
if (cypress.$('.row > .text-right > .btn').length > 0) {
cy.get('.row > .text-right > .btn').click();
}
the problem here is that cypress aborts the test if the button doesn't exist but that's exactly when cypress shouldn't abort, it should do nothing and continue.
I need a solution for
if (element.exists) {
cy.get(element).click();
}
Upvotes: 10
Views: 12496
Reputation: 651
Cypress is designed to be deterministic, so doesn't naturally lend itself flow-wise to conditional existence testing. Here's something common I do :
cy.get('body').then(($body) => {
if ($body.find('*[id*="Continue"]').length > 0)
$body.find('*[id*="Continue"]').click());
})
In our product we have Popup notes with a Continue button everywhere, which while very useful to our users is a giant pain in the behind for automation if you're not testing Popup notes. The code above we call after every cy.visit() or click on an app tab. Basically, once you have the Body object you can do all the conditionals and branching of tests you like. Now to be clear that's not really how the Cypress folks intend the tool to be used, but hey we all have our own methods and styles.
Upvotes: 0
Reputation: 18634
One way you do it is to get the parent of the element in question, which you know would be displayed every time.
cy.get('parent element').then(($ele) => {
if ($ele.find('.row > .text-right > .btn').length > 0) {
cy.get('.row > .text-right > .btn').click()
} else {
//Do Something
}
})
Upvotes: 6