0
0
Cypresstesting~5 mins

Length assertions in Cypress

Choose your learning style9 modes available
Introduction

Length assertions check if a list or group of items has the right number. This helps make sure your app shows the correct amount of things.

Check if a list of search results shows the expected number of items.
Verify the number of buttons on a page matches the design.
Confirm the number of rows in a table is correct after loading data.
Ensure a dropdown menu has the right number of options.
Test that a form shows the correct number of error messages.
Syntax
Cypress
cy.get('selector').should('have.length', expectedNumber)

Use cy.get() to find elements by CSS selector.

should('have.length', number) checks the count of matched elements.

Examples
Check that there are exactly 5 <li> items on the page.
Cypress
cy.get('li').should('have.length', 5)
Verify that 3 elements with class button exist.
Cypress
cy.get('.button').should('have.length', 3)
Assert that there are 4 checkboxes on the form.
Cypress
cy.get('input[type="checkbox"]').should('have.length', 4)
Sample Program

This test visits a sample page and checks that the list with class action-list has exactly 8 items.

Cypress
describe('Length Assertion Example', () => {
  it('checks the number of list items', () => {
    cy.visit('https://example.cypress.io/commands/actions')
    cy.get('.action-list > li').should('have.length', 8)
  })
})
OutputSuccess
Important Notes

Length assertions are useful to confirm UI elements appear as expected.

If the length does not match, Cypress will automatically retry until timeout before failing.

Use descriptive selectors to avoid flaky tests.

Summary

Length assertions check the count of elements on the page.

Use should('have.length', number) with cy.get().

This helps verify UI shows the right amount of items.