Cypress: Finding number of elements without throwing error

Viewed 1054

I need to find the number of elements present on a web page with a given locator(cy.get() or cy.xpath()). If the element is not present with the given locator, then it should not Fail the test.

I have tried cy.get(), cy.find(), cy.xpath(): all of them fails the test in case the element is not found on web page. I have tried to use cy.get('body').find('loc').length; But it also fails the test.

The below code works, but i am not able to use the value of x out side the loop. And scenario is as such that i cant put all of my code inside then().

let x = 0;
 cy.get("body").then(($body) => {
 x = $body.find("element").length;
 cy.log(`inside then: `,x);
})
cy.log(`outside then: `,x);

Expected: inside then: ,1 outside then: ,1

Actual: inside then: ,1 outside then: ,0

3 Answers

You can try using .its() function to retrieve a value of length property:

cy.get("body").its("length");
let x = 0;
 cy.get("body")
.then( 
  ($body) => {
  x = $body.find("element").length;
  cy.log(`inside then: `,x);
})
.then( 
  () => {
  cy.log(`outside then: `,x);
} )

You need to wait for the x update at x = $body.find("element").length;
The eventloop looks like :
1. let x = 0;
2. cy.log('outside then: ',x); - x =0;
3. x = $body.find("element").length;
4. cy.log('inside then: ',x);

Not clear what you want to achieve but I assume you want to test the total no of elements available. And if none then should not through error. If this is correct then this might help:

let x = 0;
function anyName() {
  return cy.get("body").then($body => {
    x = $body.find("element").length;
    if (x > 0) {
      cy.log(`Total no of elements found: ${x}`);
    } else {
      cy.log("Element is not available");
    }
  });
}
anyName();
Related