When using Cypress for automated testing, checking if multiple elements on the page contain specific content is a common requirement. To achieve this, we can employ various methods. Below, I will detail some of these methods and provide practical code examples.
1. Using contains with each for iteration
Cypress provides a contains method to locate elements that contain specific text. When checking multiple elements, we can combine it with the each method to iterate through them.
For example, suppose we want to check all product names in a product list for the word 'Apple':
javascriptcy.get('.product-name').each(($el) => { cy.wrap($el).contains('Apple'); });
In this example, .product-name is the CSS class used for each product name. The each function iterates over all matching elements, and we use wrap to wrap each element before verifying if it contains the text 'Apple'.
2. Using should with contain assertion
Another approach is to use the should method with the contain assertion. This can be directly applied to a set of elements to verify that each contains specific content.
For example, again with the product list, check if all product names contain 'Apple':
javascriptcy.get('.product-name').should('contain', 'Apple');
This method is more concise, and should('contain', 'Apple') ensures that all elements matching .product-name contain the text 'Apple'.
3. Using filter method
If you only want to perform additional operations on elements containing specific text, you can use the filter method to select these elements.
javascriptcy.get('.product-name').filter(':contains("Apple")').should('have.length', 5);
In this example, we filter out all product name elements containing 'Apple' and assert that there are exactly 5 such elements.
The following are several common methods in Cypress for checking if multiple elements contain specific content. By combining methods such as contains, each, should, and filter, we can flexibly handle various requirements for checking element content. In practical test scripts, you can select the most appropriate method based on specific testing scenarios and requirements.