How to Use cy.get in Cypress for Element Selection
Use
cy.get in Cypress to select one or more DOM elements by CSS selectors for testing. It waits automatically for elements to appear and returns them for further commands or assertions.Syntax
The basic syntax of cy.get is cy.get(selector, options). The selector is a string with a CSS selector to find elements on the page. The optional options object can customize timeout or log behavior.
This command yields the matched element(s) for chaining further Cypress commands or assertions.
javascript
cy.get('selector', { timeout: 10000 })
Example
This example shows how to use cy.get to find a button by its class and click it, then check if a message appears.
javascript
describe('cy.get example test', () => { it('finds a button and clicks it', () => { cy.visit('https://example.cypress.io') cy.get('.btn-primary').click() cy.get('#message').should('contain.text', 'Success') }) })
Output
Test passes if the button with class 'btn-primary' is found, clicked, and the element with id 'message' contains 'Success'.
Common Pitfalls
Common mistakes when using cy.get include:
- Using incorrect or overly broad selectors that match no elements or too many elements.
- Not waiting for elements to appear before interacting, though
cy.getretries by default. - Trying to use
cy.getoutside of a test or beforecy.visit.
Always use specific, stable selectors like data attributes (data-cy) for reliable tests.
javascript
/* Wrong: too generic selector */ cy.get('button').click() // May click wrong button /* Right: specific selector */ cy.get('[data-cy="submit-button"]').click()
Quick Reference
Tips for using cy.get effectively:
- Use CSS selectors or data attributes to target elements.
cy.getautomatically retries until timeout (default 4s).- Chain commands after
cy.getto interact or assert. - Use options to customize timeout or logging.
Key Takeaways
Use cy.get with CSS selectors to find elements for testing.
cy.get waits and retries automatically until elements appear or timeout.
Prefer specific selectors like data attributes for stable tests.
Chain commands after cy.get to interact or check elements.
Avoid overly broad or incorrect selectors to prevent flaky tests.