Test the number of elements in a list using Cypress?

nick asked this question 6 months ago
nick on Mar 22

On my React website, I have a basic <ul> list:

  <li>Element 1</li>
  <li>Element 2</li>
  <li>Element 3</li>
  <li>Element 4</li>

But those elements are dynamically generated based on different scenarios in my application.

In Cypress, I need to test the number of elements in that list. Sometimes there should only be one, other times two, and so on.

Is there a length feature in Cypress? Or how would I do this?

2 suggested answers
coderguy on May 14

You'll want to find the list and use the have.length Cypress method to test how many items are in the list:

Something like this:

  .should('have.length', 4);

This would grab your <ul> list and assert that there are 4 <li> elements in the list.

Read more about the length property here: https://docs.cypress.io/guides/references/assertions#Length.

0 replies
moon_man41 on May 14

Yes, Cypress has a have.length assertion method.

Read more in their docs.

0 replies