Question
Answer and Explanation
Cypress provides several ways to select elements based on their text content. This is extremely useful for creating robust and readable tests. Here are the most common methods:
1. Using `cy.contains()`:
- The `cy.contains()` command is the most straightforward way to find an element containing specific text. It searches through the DOM tree for an element that includes the provided text, and it also ensures the element is visible before taking any action.
- Example: If you want to click on a button that contains the text "Submit," you would write:
cy.contains("Submit").click();
- `cy.contains()` is versatile, because it can be used with or without a specific selector. If you know the element type you can use it like this:
cy.contains('button', "Submit").click();
2. Using `:contains()` Selector:
- This is another way to select elements by their text content using Cypress selector syntax. It is more direct when used with other selectors, such as selecting a specific tag.
- Example: To find a <li>
element containing the text "Item 1," you could use:
cy.get('li:contains("Item 1")').should('be.visible');
3. Using Regex with `cy.contains()`:
- Sometimes, you need to match text that follows a pattern rather than an exact string. `cy.contains()` supports regular expressions.
- Example: To find an element containing text that starts with the word "Product" followed by a number, you could use:
cy.contains(/^Product \d+/).should('be.visible');
4. Text-based Assertions:
- Beyond selecting, Cypress also facilitates text-based assertions. You can check that an element contains, or does not contain, specific text. It's often used with `cy.get()`, followed by an assertion.
- Example: To check that a paragraph element with an ID "message" contains the text "Success," you would use:
cy.get('#message').should('contain', 'Success');
5. Using `invoke('text')`:
- In some cases, you need to work with the exact text of an element, rather than simply selecting elements containing certain words. You can use `invoke('text')` to access this text, and then chain assertions on the text
- Example: To get the text of an element with an ID of "title" and check if it is exactly "Dashboard," you can use:
cy.get('#title').invoke('text').should('eq', 'Dashboard');
Important Considerations:
- Text-based selectors are convenient but are susceptible to changes in UI text. For more stable tests, use data attributes or specific IDs where possible. Avoid using text-based selectors when the UI text is likely to change.
- `cy.contains()` automatically ensures the element is visible before action. When using `cy.get()` with a `:contains()` selector, ensure you add `.should('be.visible')` to have the same effect.
By understanding and using these Cypress selector methods effectively, you can create tests that are not only robust, but also easier to read and maintain.