How to Assert Element Count in Cypress Tests
In Cypress, you can assert the number of elements by using
cy.get(selector).should('have.length', count). This checks that the selected elements match the expected count exactly.Syntax
The basic syntax to assert element count in Cypress is:
cy.get(selector): Selects elements matching the CSS selector..should('have.length', count): Asserts the number of matched elements equalscount.
javascript
cy.get('selector').should('have.length', expectedCount)
Example
This example shows how to check that a list has exactly 3 items using Cypress.
javascript
describe('Element count assertion', () => { it('checks that the list has 3 items', () => { cy.visit('https://example.cypress.io/commands/actions') cy.get('.action-list > li').should('have.length', 3) }) })
Output
Test passes if exactly 3 <li> elements are found inside .action-list; otherwise fails.
Common Pitfalls
Common mistakes when asserting element count include:
- Using
cy.get(selector).should('have.length', count)before the elements are loaded, causing flaky tests. - Using incorrect selectors that match more or fewer elements than expected.
- Confusing
have.lengthwithhave.length.greaterThanor other assertions.
Always ensure the page is fully loaded or the elements are visible before asserting count.
javascript
/* Wrong: Asserting count before elements appear */ cy.get('.items').should('have.length', 5) // May fail if elements load late /* Right: Wait for elements or use retries */ cy.get('.items').should('have.length', 5)
Quick Reference
| Command | Description |
|---|---|
| cy.get('selector').should('have.length', n) | Assert exactly n elements match the selector |
| cy.get('selector').should('have.length.greaterThan', n) | Assert more than n elements match |
| cy.get('selector').should('have.length.lessThan', n) | Assert fewer than n elements match |
| cy.get('selector').should('exist') | Assert at least one element exists |
Key Takeaways
Use cy.get(selector).should('have.length', count) to assert exact element count.
Ensure elements are loaded before asserting to avoid flaky tests.
Use correct and specific selectors to target the right elements.
Cypress automatically retries assertions until they pass or timeout.
Use length comparison variants for flexible count checks.