javascriptcypresscypress-conditional-testing

Do stuff according to whether an element exists or not


I want to know whether an element exists or not and do stuff according to that. I tried many options but failed. For example:

cy.get(deleteCellButtonLocator).then(($el) => {
    if ($el.length > 0) { //found
        cy.log(cellName + ' exists. Deleting...');
    } else { //not found
        console.error('Element not found');
    }
});

This one enter only the found block, but not the 'not found' block. It simply fails on AssertionFailure and stops execution. Why?


Solution

  • Setting timeout to 0 just makes it fail quicker.

    One way to do it is to add an assertion that modifies the fail behavior. Cypress runs the whole queue as single command.

    It does look-ahead checks to see if the get() should be negated. It happens that returning undefined in an assertion also changes the get() query to stop it from failing.

    The subject is passed on the the next command in the queue where you can perform the existence check.

    cy.get(deleteCellButtonLocator)
      .should(() => undefined) //           <-- stops get() from failing
      .then(($el) => {
        if ($el.length > 0) { //found
            cy.log(cellName + ' exists. Deleting...');
        } else { //not found
            console.error('Element not found');
        }
    })