Traversing elements in Cypress is a common operation that helps us select and manipulate a set of elements on the page. Cypress offers multiple methods for traversing DOM elements. Below, we'll introduce several commonly used methods and their use cases.
Using .each() to Iterate Over Elements
The .each() method allows you to iterate over a collection of elements and perform operations on each element. This is particularly useful when applying the same test logic to each element.
Example: Suppose we want to verify that the text of each item in a list meets the expected value:
javascriptcy.get('.list-item').each(($el, index, $list) => { cy.wrap($el).should('contain.text', `Item ${index + 1}`); });
Using .eq() to Select Specific Elements
When you need to select a specific element from a collection, use the .eq() method. This method accepts an index parameter and returns the element at that position.
Example: If you only want to verify the third item in the list:
javascriptcy.get('.list-item').eq(2).should('contain', 'Item 3');
Using .filter() to Filter Elements
The .filter() method allows you to narrow down a collection to elements matching specific criteria.
Example: Filtering elements with a specific class name:
javascriptcy.get('.list-item').filter('.special').should('have.length', 1);
Using .find() to Locate Child Elements
To find specific child elements within the descendants of a selected element, use the .find() method.
Example: Verifying child elements within each list item:
javascriptcy.get('.list-item').find('.child').should('exist');
Using .next(), .prev(), and .siblings() to Traverse Related Elements
These methods select sibling elements based on the current element's position in the DOM.
Example: Selecting the element immediately following a specific element:
javascriptcy.get('.first-item').next().should('have.class', 'second-item');
With these methods, Cypress enables flexible and efficient traversal and manipulation of DOM elements, which is essential for automated testing. These examples illustrate how to apply these methods in various scenarios to achieve testing objectives.