0

I need to check multiple pages for whether a list exists, and if so, get the length of the list. This works fine except some pages do not have lists (this is intentional). Is there any way I can use .should('exist') to check if the list is there and if so check it, otherwise just continue?

I currently have this test:

if (cy.get('.mt-5').should('exist')) {
    cy.get('.mt-5')
        .find('li')
        .then(($listItems) => {
            const listLength = $listItems.length;
            cy.wrap(listLength).as('listLength');
        });
}

however, this just causes a timeout when it gets to the if statement as it is looking for .mt-5 which does not always exist.

Woden
  • 168
  • 6

1 Answers1

3

The command cy.get('.mt-5') can't be used as a test in the if() statement, but you can try using Cypress.$('.mt-5') instead.

The problem will be that you loose the retry built in to cy.get(). It would be preferable not to use a conditional statement in the test, instead try to set up the test condition such that you always have that element.

if (Cypress.$('.mt-5').length) {
    cy.get('.mt-5')
        .find('li')
        .then(($listItems) => {
            const listLength = $listItems.length;
            cy.wrap(listLength).as('listLength');
        });
}

If you really have to use conditional testing, and need to wait for the .mt-5 element, there is a way to add your own retry via element polling.

See How to check for an element that may not exist using Cypress

Lola Ichingbola
  • 3,035
  • 3
  • 16