How to Test Lists of Items in Cypress
This guide shows you how to verify the contents, order, and state of lists of items in Cypress, a popular end-to-end testing framework. You’ll learn practical patterns for asserting on list items, filtering them, and handling dynamic lists, so your tests stay reliable even as your app changes.
What You’ll Need
- A working Cypress setup (Cypress installed and configured in your project).
- Basic familiarity with Cypress commands like
cy.get()andcy.contains(). - An application with at least one list (e.g., a
<ul>,<ol>, or a table body) to test against.
Step-by-Step
- Identify the list selector. Open your app in the Cypress Test Runner and use the selector playground to find a stable selector for the list container. Prefer data attributes like
[data-testid="item-list"]over classes that might change. - Get the list items. Use
cy.get('[data-testid="item-list"] li')to select all items. If your list is a table, usetbody trinstead. Store the result in a variable if you need to reuse it:const items = cy.get('...'). - Assert the number of items. Use
.should('have.length', 3)to verify the expected count. For dynamic lists, you can assert a minimum:.should('have.length.at.least', 1). - Check the text content of items. Use
.should('contain', 'Item text')to check that a specific item exists. To check multiple items, chain.should('contain', 'First')and.should('contain', 'Second'). - Verify the order of items. Use
.each()to iterate over items and compare their text to an expected array. For example:const expected = ['Apple', 'Banana', 'Cherry']; cy.get('li').each(($el, index) => { cy.wrap($el).should('contain', expected[index]); }); - Filter items by text. Use
.contains('Banana')to get a specific item, then assert on it. For example:cy.get('li').contains('Banana').should('have.class', 'selected'). - Check that an item is visible or hidden. Use
.should('be.visible')or.should('not.be.visible')on the item or its container. - Handle async updates. If the list loads after an API call, use
cy.intercept()to wait for the response, or use.should()with a retryable assertion like.should('have.length', 5)which Cypress retries until timeout.
Common Mistakes
- Using brittle selectors. Relying on CSS classes that change often. Use data attributes or stable structural selectors.
- Assuming list order. If the order isn’t guaranteed, don’t assert on it. Instead, check that all expected items exist using
.should('contain', ...). - Forgetting to wait for data. If the list is populated asynchronously, your test might run before the items appear. Use
cy.intercept()or retryable assertions. - Using
cy.contains()on the whole page. This can match unintended elements. Scope it to the list:cy.get('ul').contains('Item'). - Not cleaning up state. If your test adds items to a list, ensure you remove them or reset the database in a
beforeEach()hook.
Tips
- Use
data-testidattributes. They are immune to styling changes and make your tests more robust. - Leverage
.should()with callbacks. For complex assertions, you can pass a function:.should(($lis) => { expect($lis).to.have.length(3); }). - Test empty states. Verify that the list shows a message when there are no items:
cy.get('.empty-message').should('be.visible'). - Use
cy.wrap()inside.each(). This ensures Cypress commands work correctly within the loop. - Keep tests focused. Test one behavior per test case. For example, one test for count, another for order, and another for filtering.
Troubleshooting
- Test fails because items are not found. Check the selector in the Test Runner’s selector playground. Ensure the list is rendered after the page loads. Add a
cy.wait()or usecy.intercept()to wait for API calls. - Test passes locally but fails in CI. This is often due to timing. Increase the default timeout in
cypress.config.jsor use{ timeout: 10000 }on the failing assertion. - Items are duplicated or missing. Verify your app’s logic. Use
cy.log()to print the number of items found:cy.get('li').then($lis => cy.log($lis.length)). - Order assertion fails intermittently. If the order is not guaranteed, remove the order check. If it is, ensure your app sorts the list before rendering.
- Cannot use
.each()with async code. Cypress commands are asynchronous, but.each()handles them. If you need to perform a Cypress command inside the loop, usecy.wrap()as shown.
Frequently Asked Questions
How do I check that a list contains a specific item?
Use cy.get('ul').contains('Item text'). This will pass if any item contains that text.
How do I assert that a list is empty?
Use cy.get('li').should('have.length', 0) or check for an empty message element.
How do I test a list that loads after a delay?
Use cy.intercept('GET', '/api/items').as('getItems') before triggering the load, then cy.wait('@getItems') after.
Can I test the order of list items?
Yes, use .each() and compare the text of each item to an expected array. Only do this if the order is deterministic.
How do I click on a specific item in a list?
Use cy.contains('Item text').click(). If there are multiple matches, use .first() or .eq(index).
What is the best way to select list items?
Use a dedicated data-testid attribute on the list container and then select children with li or tr. This is robust against CSS changes.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.