乐闻世界logo
搜索文章和话题

How to get array of specific attributes values in cypress

1个答案

1

When using Cypress for automated testing, if you need to retrieve an array of specific attributes on the page, you can leverage Cypress's .each() method to iterate over each element and utilize the .invoke() method to fetch attribute values. Here is a concrete example demonstrating how to achieve this.

Suppose you have a page with multiple <input> elements, each having a data-id attribute. You want to retrieve all the values of these data-id attributes and store them in an array.

Example Code

javascript
// Define an empty array to store data-id attribute values let dataIds = []; // Use Cypress's `cy.get()` method to get all input elements // Then use `.each()` to iterate over each element cy.get('input').each(($el) => { // Use `.invoke()` to retrieve the `data-id` attribute value for each element cy.wrap($el).invoke('attr', 'data-id') .then(dataId => { // Add the retrieved attribute value to the array dataIds.push(dataId); }); }).then(() => { // After completing all iterations, you can use the dataIds array here // For example, log the array or perform assertions console.log(dataIds); // Log all data-id values expect(dataIds).to.have.length.above(0); // Assert the array is not empty });

Explanation

  1. Define Array: First, define an empty array dataIds to store the data-id attribute values of each element.

  2. Get Elements: Use cy.get('input') to select all <input> elements on the page.

  3. Iterate Elements: Use the .each() method to iterate over these elements. For each element, wrap the jQuery element as a Cypress object using cy.wrap($el) so you can apply Cypress commands.

  4. Retrieve Attribute Values: Use .invoke('attr', 'data-id') to fetch the data-id attribute value of the current element.

  5. Store Attribute Values: Within the .then() function, after retrieving the attribute value, add it to the dataIds array.

  6. Use the Array: After all elements have been processed, use .then() to handle the dataIds array, such as logging or performing assertions.

This approach is not limited to the data-id attribute; it can be used to retrieve any attribute collection by simply adjusting the attribute retrieval part to the corresponding attribute name.

2024年6月29日 12:07 回复

你的答案