DEV Community


Posted on

Cypress - counting the number of elements on a page

A scenario you may face is when you want to count how many of a certain element is on a page when using cypress. There is a simple solution for this, especially if you use data-cy in your code to ease testing.

the command: cy.get('[data-cy="element"').should('have.length', 2); should get you the number of a certain element on a page.

If you do not use data-cy's, then finding by class should work: cy.get('class_name').should('have.length', 2);. Furthermore, if you want to find the number of elements in a table, you can do cy.get('table_name').find('tr').should('have.length', 2);

A more advanced way of finding elements can be done by this method: cy.get('item:visible:contains("text")').should('have.length, 2); where you are using contains to find all the items with a certain text you want. The visible flag has to be used as contains can only find visible DOM elements.

Also, remember, you can simplify, without having to use cy.get() each time, especially if running multiple tests by declaring your items in a file and importing them into your test file as shown below.

const page = {
   item: () => cy.get('item'),

module.exports = page;
Enter fullscreen mode Exit fullscreen mode

Then you can run page.item().should('have.length', 2); which can be considered better practice.

More information at

Top comments (0)