Counting Items in Cypress: A Practical Guide

Counting Items in Cypress: A Practical Guide

21 May 2024 Stephan Petzl Leave a comment Tech-Help

When working with Cypress for end-to-end testing, a common requirement is to count the number of elements within a specific selector. For instance, you might want to count the number of rows in a table to ensure the correct rendering of data. This article will guide you through the most effective methods to achieve this.

Understanding the Basics

Cypress offers several ways to count elements within a selection. Let’s explore the most efficient and commonly used methods to count the number of rows in a table with a class of datatable.

Using should('have.length', n)

One of the simplest and most effective ways to count elements is by using the should('have.length', n) assertion. This method directly asserts the length of the elements found.

      cy.get('.datatable').find('tr').should('have.length', 4)

This approach is straightforward and avoids any intermediate steps, making it both efficient and easy to understand.

Using its('length')

Another method to count elements is by using the its('length') property. This can be particularly useful when you need to perform additional assertions on the length.

      cy.get('.datatable').find('tr').its('length').should('eq', 4)
      cy.get('.datatable').find('tr').its('length').should('be.gte', 4)

This method gives you more flexibility and allows for more complex assertions if needed.

Using then() for Dynamic Results

For scenarios where the number of elements may vary or need to be dynamically checked, using then() can be very effective.

        .then(listing => {
          const listingCount = Cypress.$(listing).length;

This method allows you to store the count of elements in a variable and use it for further assertions or operations.


Counting elements in Cypress can be achieved through multiple methods, each with its own advantages. Whether you choose should('have.length', n) for simplicity, its('length') for flexibility, or then() for dynamic counting, Cypress provides robust tools to handle these requirements.

Enhance Your Testing with Repeato

While Cypress is a powerful tool for end-to-end testing, you might find that incorporating a no-code solution like Repeato can further streamline your testing process. Repeato allows you to create, run, and maintain automated tests for your iOS and Android apps without writing a single line of code. Its computer vision and AI capabilities ensure fast and accurate test execution. Additionally, Repeato’s intuitive test recorder and scripting interface make it an ideal choice for both beginners and advanced testers.

For more information on how Repeato can enhance your testing workflow, visit our documentation or check out our latest updates on the blog.

Like this article? there’s more where that came from!