How to get the number of elements with Cypress
Recently, when working with Cypress again, I’ve met the issue that I cannot get the number of elements with Cypress. If the element is not found, Cypress will fail the test, which is not the result. In this blog, let’s see how you can do it with Cypress.
Usually, if you have experience working with Selenium, you might think the below code is the one that gives you the number of elements for the given locator.
const numberOfElements = cy.get('css-locator').its('length');
But no, this line of code does not work as expected. There are two problems with this code:
- Cypress is asynchronous, which makes it return the value right away before actually executing it -> the value of the number of elements will be `chainable<number>`, not the number
- After Cypress finishes evaluating, it will execute the code. This time it will throw the timeout error if the element does not exist.
So how do you go through this problem?
First, you need to make sure you have a parent element that must exist, then find your elements in it using a then block.
getLengthOfElements(cssLocator: string){
cy.get('body').then((element) => {
element.find(cssLocator);
})
}
When this function is executed, if the element with csslocator
value is not found, Cypress will not throw an exception.
In your test file, you can call this function and apply the check for the number of elements like below
getLengthOfElements('id*="index"').then((value) => {
if(value.length==15){
cy.log('TRUE');
}else if (value.length==0){
cy.log('Not found');
}
});
The result.
If the number of elements is 0, the test still passes and logs “Not found”.
get body
log Not found
If the number of elements exceeds 0, the test is passed with the log “TRUE”.
get body
log TRUE
For the full code, please check out practice-cypress repository.
Hope it helps~~
Happy testing