Cypress: Count the total number of elements on a page

Anshita Bhasin
2 min readNov 3, 2022

--

In this blog, we will learn how to find the length of elements on a page in Cypress.

Sharing 3 approaches based on different scenarios:

  1. Scenario — When the expected length is known

We can find the count of elements on a page and compare it with the fixed expected length by using “cy.get(locator).should(have.length,count)”.

Below is the sample code:

Code Explanation:

In the above code, we pass the locator and then use “.should(have.length,count)”. If we know the expected count, we should use the above approach to verify whether the expected count matches the actual count.

Output:

2. Scenario: When you want to find the length and then re-use it in further tests

There can be scenarios where we want to find the length and then perform some calculations on it or use it in different functions. In that case, any of the below approaches can be used.

Approach1:

Using .length

Code Explanation:

In the above code, we store the element's length in a variable “length” and then re-use it in different tests. We are fetching the values which have text as “United Arab Emirates”. If we want to perform further validation based on the count. We can do it by following the above approach.

Output:

Approach2:

Using Cypress.$value.length

In the above code, we are finding the locator and then we use Cypress.$value.length to fetch the length.

Output:

Conclusion:

In this blog, we saw 3 different approaches by which we can get the length of elements on a page in Cypress. Depending on the operation we perform, we can choose any of the above methods.

Thanks for reading! Happy learning !! — AB

Thanks, Naveen AutomationLabs for the guidance!

To check the code, you can refer — https://github.com/Anshita-Bhasin/Cypress10_AB/blob/main/cypress/e2e/findLength.cy.js

Anshita Bhasin
Sr. Automation Engineer

GitHub | LinkedIn | Twitter | Youtube

--

--

Anshita Bhasin

QA Chapter Lead at Proptech company in Dubai.. Here to share and learn new things! Youtube => ABAutomationHub