Manspof
Manspof

Reputation: 357

Cypress: Check if element exists & throw an exception when element doesn't

I'm trying to check if an element exists or not. If the element exists, I want to click on the button X, I want to click on the button Y.

However, when the element does not exist Cypress throws an exception and it stops the test.

enter image description here

Code Sample:

let elementKey = '#up-picker'
Cypress.get('body').then($res=>{
  if($res.find(elementKey).length>0){
   // click on button X
  }else{
    // click on button Y
  }
})

I have an element with this id, but sometimes because the logic in the UI changes it, Cypress can find this element.

I checked more posts in Stackoverflow and no answer works for me.

Upvotes: 1

Views: 380

Answers (1)

Leonid Sviderskii
Leonid Sviderskii

Reputation: 46

What's working for my tests (close to your example):

cy.get('body').then($body => {
  if ($body.find('your-selector').length) {
    // do stuff
  }
});

Upvotes: 1

Related Questions