How to Use cy.find in Cypress for Element Searching
In Cypress,
cy.find is used to search for descendant elements within a previously selected element. It helps narrow down the search scope by chaining from a parent element to find child elements matching a selector.Syntax
The cy.find command is chained off a parent element to locate child elements matching a CSS selector. It returns the found elements wrapped in a Cypress chainable for further commands.
Syntax parts:
parentElement: The Cypress chainable containing the parent element..find(selector): Finds descendant elements matching the CSS selector inside the parent.
javascript
cy.get('parentSelector').find('childSelector')
Example
This example shows how to find a button inside a specific container and click it.
javascript
cy.get('.container').find('button.submit').click()
Output
Test passes if the button with class 'submit' inside '.container' is found and clicked successfully.
Common Pitfalls
Common mistakes when using cy.find include:
- Using
cy.findwithout chaining from a parent element, which causes errors. - Confusing
cy.findwithcy.get:cy.findsearches only inside the previous subject, whilecy.getsearches the whole document. - Using overly broad selectors that match multiple elements unexpectedly.
javascript
/* Wrong: cy.find used alone */ cy.find('button') // This will fail /* Right: chained from a parent */ cy.get('.form').find('button')
Quick Reference
| Command | Description |
|---|---|
| cy.get('selector') | Selects elements from the entire page |
| cy.get('parent').find('child') | Finds child elements inside the parent element |
| cy.find('selector') | Must be chained; finds descendants of previous subject |
| cy.get('selector').click() | Clicks the selected element |
| cy.get('selector').find('child').click() | Clicks a child element inside the parent |
Key Takeaways
Use cy.find only after selecting a parent element with cy.get or another command.
cy.find narrows the search to descendants of the previous element, unlike cy.get which searches the whole page.
Always use specific selectors to avoid matching multiple unintended elements.
Avoid calling cy.find alone; it must be chained from a previous subject.
Use cy.find to write clearer, more maintainable tests by limiting search scope.