Open In App

Cypress - each() Method

Last Updated : 24 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The each() method in Cypress allows us to iterate over a set of elements and perform actions or assertions on each element. It is particularly useful when working with multiple DOM elements, such as a list of items, and we want to interact with or verify each of them individually.

Usage of each() Method

The each() method is used when we want to loop through a collection of DOM elements and perform some action on each element in the collection. This can be useful for verifying lists, checking content, or interacting with multiple elements without repeating code.

Syntax:

cy.get(selector).each((element, index, $list) => { ... })

Arguments:

  • selector (Required): A CSS selector that targets a group of elements.
  • element (Required): The current element in the iteration.
  • index (Optional): The index of the current element in the collection.
  • $list (Optional): The full list of elements being iterated over.

Examples

Example 1: Iterating Through a List of Items

In this example, we’ll use the each() method to iterate over a list of items and assert their content.

  • HTML File (index.html):
    Save this file in the root directory of the local server (e.g., localhost:3000).
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>List Example</title>
</head>
<body>
    <ul id="itemList">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ul>
</body>
</html>
  • Cypress Test File (each_test1_spec.js):
    Save this file in the cypress/e2e folder (for Cypress v10 and above) or cypress/integration folder (for older versions).
JavaScript
describe('Using `each()` to iterate over a list of items', () => {

  beforeEach(() => {
    // Visit the HTML file hosted on localhost
    cy.visit('http://localhost:3000');
  });

  it('should iterate through each list item and assert its content', () => {
    // Get all the list items within the UL and iterate over each using each()
    cy.get('#itemList li').each((item, index, $list) => {
      // Assert that the content of each list item is correct
      cy.wrap(item).should('have.text', `Item ${index + 1}`);
    });
  });

});

Explanation of the Test:

  • HTML Structure: The HTML file contains a simple list of items inside a <ul> element with the ID itemList.
  • Cypress Test: The each() method is used to iterate over the <li> elements within the #itemList and assert that each item’s content matches the expected text (e.g., Item 1Item 2, etc.).

Output:

each
Output

The test will run successfully, demonstrating the use the each() method to iterate over a list of items and assert their content.

Example 2: Interacting with Elements in a Collection

In this example, we’ll use the each() method to click on each button in a collection and verify that the corresponding message is displayed.

  • HTML File (index.html):
    Save this file in the root directory of the local server (e.g., localhost:3000).
JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Button Click Example</title>
</head>
<body>
    <button class="showMessage">Show Message 1</button>
    <button class="showMessage">Show Message 2</button>
    <button class="showMessage">Show Message 3</button>

    <div id="message"></div>

    <script>
        const buttons = document.querySelectorAll('.showMessage');
        const messageDiv = document.getElementById('message');

        buttons.forEach((button, index) => {
            button.addEventListener('click', () => {
                messageDiv.innerText = `Message ${index + 1} displayed!`;
            });
        });
    </script>
</body>
</html>
  • Cypress Test File (each_test2_spec.js):
    Save this file in the cypress/e2e folder (for Cypress v10 and above) or cypress/integration folder (for older versions).
JavaScript
describe('Using `each()` to interact with buttons and verify actions', () => {

  beforeEach(() => {
    // Visit the HTML file hosted on localhost
    cy.visit('http://localhost:3000');
  });

  it('should click each button and verify the correct message is displayed', () => {
    // Get all buttons with the class 'showMessage' and iterate over each using each()
    cy.get('.showMessage').each((button, index) => {
      // Click each button
      cy.wrap(button).click();

      // Verify that the corresponding message is displayed after each click
      cy.get('#message').should('have.text', `Message ${index + 1} displayed!`);
    });
  });

});

Explanation of the Test:

  • HTML Structure: The HTML file includes three buttons, each of which triggers a different message when clicked.
  • Cypress Test: The each() method is used to iterate over the buttons, click each one, and then verify that the corresponding message is correctly displayed.

Output:

each1
Output


The test will run successfully, demonstrating the use the each() method to click on each button in a collection and verify that the corresponding message is displayed.

Running the Test

  1. Start the Local Server: Ensure that the local server is running and serving the index.html file at http://localhost:3000.
  2. Open Cypress Test Runner: Run the following command in our terminal:
    npx cypress open
  3. Run the Test: In the Cypress Test Runner, click on the test file (each_test1_spec.js or each_test2_spec.js) to execute the test and view the results.

Conclusion

In this article, we explored the each() method in Cypress and how it can be used to iterate over multiple elements in a DOM. Whether we need to verify content or interact with each element in a collection, each() simplifies the process by reducing repetitive code and enabling more dynamic test cases.


Explore