Search code examples
javascriptcypress

Cypress: if element exist then do something


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();
    }

Solution

  • 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
        }
    })