In Cypress, to click on nested elements containing specific text, you can use a series of commands to locate and interact with the element. Here is a specific step-by-step example, assuming the text we want to click is "Confirm Action".
First, determine the selector. If the text is unique, you can directly use the :contains() selector to locate it, then use the .click() command to simulate the click action.
Here is an example of a Cypress test code:
javascript// Locate the nested element containing the text "Confirm Action" and click it cy.contains('Confirm Action').click();
If the text is not unique or appears across multiple nested levels, you may need more specific selectors to narrow the search. For example:
javascript// Locate the child element under a specific parent containing the text "Confirm Action" and click it cy.get('.parent-selector').contains('Confirm Action').click();
In certain scenarios, if the text appears in multiple nested elements, you may need to chain commands such as .find() or .children() to further specify the element:
javascript// Locate the text within a complex nested structure cy.get('.parent-selector') // First locate the parent element .find('.child-class') // Then find child elements .contains('Confirm Action') // Locate the element containing the text .click(); // Execute the click action
Another case is when the target element is invisible or obscured by other elements, in which case the .click() command may fail. In such situations, you can use .click({ force: true }) to force click:
javascript// Force click on an invisible or obscured element cy.contains('Confirm Action').click({ force: true });
These are the fundamental approaches for clicking nested elements with specific text. In real-world applications, you may need to adjust the selectors and methods based on specific requirements. When developing automated tests, it's a good practice to use maintainable and stable selectors, such as using data-* attributes as hooks. This provides a stable way to locate elements for automated testing without affecting styles or structure.