How to Use cy.contains in Cypress for Element Selection
Use
cy.contains() in Cypress to find DOM elements that contain specific text. It searches for elements with matching text and returns the first match by default, allowing you to chain further commands or assertions.Syntax
The basic syntax of cy.contains() is:
cy.contains(text): Finds the first element containing the exact text.cy.contains(selector, text): Finds the first element matching the selector that contains the text.cy.contains(text, options): Finds element with text and applies options like matchCase.
javascript
cy.contains('Submit') cy.contains('button', 'Submit') cy.contains('Submit', { matchCase: false })
Example
This example shows how to find a button with the text 'Login' and click it, then verify a success message appears.
javascript
describe('cy.contains example test', () => { it('finds button by text and clicks', () => { cy.visit('https://example.cypress.io') cy.contains('button', 'Login').click() cy.contains('Login successful').should('be.visible') }) })
Output
Test passes if the button with text 'Login' is found and clicked, and the success message 'Login successful' is visible.
Common Pitfalls
Common mistakes when using cy.contains() include:
- Not specifying a selector when multiple elements contain the text, causing unexpected matches.
- Case sensitivity issues if
matchCaseoption is not set properly. - Using partial text without understanding it matches substrings, which can cause false positives.
javascript
/* Wrong: May match wrong element if multiple contain 'Submit' */ cy.contains('Submit').click() /* Right: Specify selector to narrow down */ cy.contains('button', 'Submit').click()
Quick Reference
| Usage | Description |
|---|---|
| cy.contains(text) | Finds first element containing exact text |
| cy.contains(selector, text) | Finds first element matching selector with text |
| cy.contains(text, { matchCase: false }) | Finds text ignoring case sensitivity |
| cy.contains(/regex/) | Finds element matching text by regular expression |
Key Takeaways
Use cy.contains() to find elements by visible text content easily.
Specify a selector with cy.contains(selector, text) to avoid ambiguous matches.
Remember cy.contains() matches substrings by default, so be precise.
Use options like matchCase to control case sensitivity.
Chain assertions after cy.contains() to verify element state or visibility.