2

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

Nishant
  • 41
  • 1
  • 6

3 Answers3

1

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

cy.get("body").its("length");
Vaidas
  • 1,494
  • 14
  • 21
  • 1
    Thanks for ur input. I tried this too. In case the element is not present then it gives the following message in Browser developer console : "Unhandled rejection CypressError: Timed out retrying" ..... but the execution stops here and the further steps are not executed and the timer on the cypress left UI keeps on running . i have set all the timeouts to 30 secs. – Nishant Jun 26 '19 at 07:08
0
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);

noobjs
  • 61
  • 5
  • agreed. but i tried to put cy.wait() outside then(), so that the code inside then() completes. But still the value of x is coming as 0 only. It executed in this sequence: let x=0 > x = $body.find("element").length; > x = $body.find("element").length; > cy.wait() > cy.log('outside then: ',x); – Nishant Jun 26 '19 at 07:15
  • you should post bigger code snippet to see whats wrong there – noobjs Jun 26 '19 at 08:55
0

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();
T Gurung
  • 333
  • 1
  • 7
  • thanks. But i need the value of x as return from the function. So that it can be used outside the loop as well. – Nishant Jun 26 '19 at 07:17
  • Please refer here to return: https://stackoverflow.com/questions/34094806/return-from-a-promise-then – T Gurung Jun 26 '19 at 14:19