0
0
CypressHow-ToBeginner ยท 3 min read

How to Select Elements in Cypress: Syntax and Examples

In Cypress, you select elements using the cy.get() command with CSS selectors or attributes. You can also use cy.contains() to find elements by their text content. These commands let you target elements to interact with or assert in your tests.
๐Ÿ“

Syntax

The main command to select elements in Cypress is cy.get(). You pass a CSS selector string to it to find elements on the page. For example, cy.get('button') selects all <button> elements.

You can also use cy.contains() to select elements that contain specific text, like cy.contains('Submit').

Selectors can be tag names, classes, IDs, attributes, or combinations.

javascript
cy.get('<selector>')
cy.contains('<text>')
๐Ÿ’ป

Example

This example shows how to select a button by its class and click it, then select a link by its text and check its visibility.

javascript
describe('Element Selection Example', () => {
  it('selects elements and interacts', () => {
    cy.visit('https://example.cypress.io')
    cy.get('.btn-primary').click()  // Select by class and click
    cy.contains('type').should('be.visible')  // Select by text and assert visibility
  })
})
Output
Test passes if the button with class 'btn-primary' is clicked and the link containing 'type' is visible.
โš ๏ธ

Common Pitfalls

Common mistakes include using overly broad selectors like cy.get('div') which select many elements and cause flaky tests. Avoid selecting by text that may change often. Also, do not chain commands without waiting for elements to appear.

Use unique selectors like data attributes (data-cy) for stable tests.

javascript
/* Wrong: Too broad selector */
cy.get('div').click()

/* Right: Use data attribute for precise selection */
cy.get('[data-cy=submit-button]').click()
๐Ÿ“Š

Quick Reference

CommandDescriptionExample
cy.get()Select elements by CSS selectorcy.get('.class-name')
cy.contains()Select element by text contentcy.contains('Submit')
cy.get() with attributeSelect by attribute valuecy.get('[data-cy=login]')
cy.find()Find child elements within a parentcy.get('form').find('input')
โœ…

Key Takeaways

Use cy.get() with CSS selectors to select elements precisely.
Use cy.contains() to select elements by visible text.
Prefer unique attributes like data-cy for stable selectors.
Avoid broad selectors that match many elements to prevent flaky tests.
Chain commands carefully and wait for elements to appear before interacting.