Test the number of elements in a list using Cypress?

Answered
nick asked this question 2 months ago
nick on Mar 22

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

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

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 9 days ago

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:

cy
  .get('ul')
  .find('li')
  .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 9 days ago

Yes, Cypress has a have.length assertion method.

Read more in their docs.

0 replies
Answered