0
0
Cypresstesting~5 mins

Best practices for selectors in Cypress

Choose your learning style9 modes available
Introduction

Selectors help tests find elements on a webpage. Good selectors make tests reliable and easy to maintain.

When writing a test to click a button on a webpage
When checking if a form input has the correct value
When verifying that a message appears after an action
When selecting a list item to test its content
When automating navigation through menus
Syntax
Cypress
cy.get('selector')

Use cy.get() to find elements by CSS selectors.

Choose selectors that are stable and unique to avoid test failures.

Examples
Selects an element with the unique ID submit-button. IDs are best for uniqueness.
Cypress
cy.get('#submit-button')
Selects an element using a custom attribute data-cy. This is a recommended practice for test selectors.
Cypress
cy.get('[data-cy=login-input]')
Selects an element with class nav-item that contains the text 'Home'. Useful when classes are shared.
Cypress
cy.get('.nav-item').contains('Home')
Selects the first button element on the page. Use carefully as order can change.
Cypress
cy.get('button').eq(0)
Sample Program

This test visits a login page, types username and password using stable selectors, clicks login, and checks for a welcome message.

Cypress
describe('Login form test', () => {
  it('should find and type in the username input', () => {
    cy.visit('https://example.com/login')
    cy.get('[data-cy=username-input]').type('testuser')
    cy.get('[data-cy=password-input]').type('password123')
    cy.get('#login-button').click()
    cy.get('.welcome-message').should('contain.text', 'Welcome, testuser')
  })
})
OutputSuccess
Important Notes

Avoid using selectors based on text that might change often.

Prefer custom attributes like data-cy for test selectors to separate test code from styling.

Do not rely on element order unless necessary, as it can make tests fragile.

Summary

Use unique and stable selectors like IDs or custom attributes.

Keep selectors simple and clear to make tests easy to read and maintain.

Test selectors should not depend on styling or text that changes frequently.