javascriptcypresscypress-conditional-testing

Can I prevent Cypress cy.get from failing if no elements are found?


I am using Cypress cy.get to grab elements, but if there are none, my test is failing. I do not want it to fail. I want it to continue. The test is simply to list the items that are there, if any.

const listItemTitle = '[data-cy-component=list-item-title]';
cy.get(listItemTitle).each(($el, index, $list) => {
  cy.wrap($el).then(($span) => {
    const spanText = $span.text();
    cy.log(`index: ` + index + ' ' + spanText);
  });
});

I would have thought, if there are no elements there - that this code would still be ok, but not so. When I run it, I get this error: CypressError: Timed out retrying: Expected to find element: '[data-cy-component=list-item-title]', but never found it.

It works fine where elements are present. If no elements are found, I want to go on & do a different test.

Here is an experiment I tried:

let count: number = Cypress.$(listItemTitle).length;
cy.log('before:' + count);
cy.get(actionsBarActionsAdd).click();
cy.get(singlePickerSearch).type('Assets' + '{enter}');
cy.get(listItemCheckboxTitle)
  .first()
  .click();
cy.toast({
  type: 'Success',
});
count = Cypress.$(listItemTitle).length;
cy.log('after:' + count);
cy.get(listItemTitle).each(($li, index, $lis) => {
  cy.log('interface no. ' + (index + 1) + ' of ' + $lis.length);
  cy.wrap($li).click();
});

This was the outcome:

18 LOG        before:0
19 GET       [data-cy-component-key="actions-add"] input
20 CLICK
21 GET       [data-cy-component=single-picker-search] input
22 TYPE      Assets{enter}
23 GET       [data-cy-component="list-item-checkbox-title"]
24 FIRST
25 CLICK
26 GET       .iziToast    toast2
27 ASSERT    expected [ <div.iziToast.iziToast-opening.fadeInUp.iziToast-theme- 
alloy.iziToast-color-green.iziToast-animateInside>, 1 more... ] to have class iziToast-color-green
28 LOG       after:0
29 GET       [data-cy-component=list-item-title]
30 LOG       interface no. 1 of 1

Conclusively shows that Cypress.$(listItemTitle).length does not count number of elements with selector: listItemTitle.

Update:

By putting a cy.wait(1000); after the Add had been executed (in my experiment) - giving the DOM time to update - the new element was found. With more specific selectors, the wait is not required


Solution

  • You can use jquery via Cypress.$ to check if any exist.

    const listItemTitle = '[data-cy-component=list-item-title]';
    if (Cypress.$(listItemTitle).length > 0) {
      cy.get(listItemTitle).each(($el, index, $list) => {
        cy.wrap($el).then(($span) => {
        const spanText = $span.text();
        cy.log(`index: ` + index + ' ' + spanText);
        });
      });
    }