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

How to get an element that has a dynamic selector in Cypress

1个答案

1

When dealing with dynamic selectors, Cypress provides several methods to retrieve elements. Dynamic selectors typically refer to elements whose class names, IDs, or other attributes may change after page load or user interaction. Below are some methods for handling dynamic selectors and locating elements:

1. Elements with Static Text Content

If the element's text content is static and unique, you can use the contains command to locate the element:

javascript
cy.contains('fixed text content');

2. Using Fixed Attributes

If certain attributes of the element are fixed, you can directly locate the element using these attributes:

javascript
cy.get('[data-cy="fixed attribute"]');

3. Regex Matching for Attributes

If attribute values follow a specific pattern, you can use regex to match these attributes:

javascript
cy.get('input[name^="input-name-prefix-"]'); cy.get('div[class*="partial-class-name"]');

4. Using Parent or Sibling Element Relationships

Sometimes, you can locate dynamic elements by finding parent or sibling elements with stable selectors:

javascript
cy.get('#parent-element-id').find('.child-element-class'); cy.get('.sibling-element-class').next('.target-element');

5. Using .invoke() and jQuery Methods

For complex selection requirements, you can use the .invoke() function combined with jQuery methods:

javascript
cy.get('.dynamic-element').invoke('attr', 'name').then((name) => { // Further logic based on name });

6. Using Callback Functions for Filtering

You can use the .filter() method and pass a callback function to further filter matching elements:

javascript
cy.get('.list-item').filter((index, element) => { return element.textContent.includes('fixed text'); });

Practical Examples

Assume there is a to-do list where each item's ID is dynamically generated when a new to-do is added. You can use a static class name and the contains method with the to-do item text content to retrieve the specific to-do element:

javascript
cy.get('.todo-list-item').contains('Buy groceries');

Alternatively, if each to-do item has a data-test-id attribute starting with a specific format, such as todo- followed by a number, you can use regex to locate the element:

javascript
cy.get('[data-test-id^="todo-"]');

Overall, the best practice is to use fixed attributes as much as possible for locating elements, such as data-* attributes, which are specifically designed for testing and are unlikely to change with application updates.

2024年6月29日 12:07 回复

你的答案