javascriptcypresscypress-conditional-testing

How to be able to handle both cases of element exists and does not exist?


I would like to have the ability to handle the situation of both cases: the element exists and does not exist.

All my trials ended with an exception when it didn't find the item and therefore I couldn't do the stuff I wanted in this case or errors that using then.catch or then.fail are not valid.

For example, my last trial is:

cy.get('.ant-breadcrumb-link').then(($element) => {
    if ($element.is(':exists')) {
        // Element exists, perform actions
        cy.log('Element exists');
        // ... your actions when the element exists ...
    } else {
        // Element does not exist, perform other actions
        cy.log('Element does not exist');
        // ... your actions when the element does not exist ...
    }
});

So when the cy.get('.ant-breadcrumb-link') fails I don't get into the then() section.

How can I achieve my goal?


Solution

  • You can always leverage jQuery when you face issues with the checking the existence of the element. I would get the document object using cy.document and use Cypress.$(jquery equivalent in cypress) for the same. A sample would look like:

    cy.document().then((document) => {
      const $element = Cypress.$('.ant-breadcrumb-link', document);
      
      if ($element.length > 0) {
        // ... your actions when the element exists ...
      } else {
        // ... your actions when the element does not exist ...
      }
    });
    

    SIDENOTE:

    cy.get() will keep on searching for the element and throws an exception if the element is not found.