0
0
Cypresstesting~10 mins

Best practices for selectors in Cypress - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a login form can be submitted using best practice selectors. It verifies that the username and password fields are found by data attributes, the submit button is clicked, and the success message appears.

Test Code - Cypress
Cypress
describe('Login form test with best practice selectors', () => {
  it('submits login form and shows success message', () => {
    cy.visit('/login')
    cy.get('[data-cy=username]').type('testuser')
    cy.get('[data-cy=password]').type('password123')
    cy.get('[data-cy=submit-button]').click()
    cy.get('[data-cy=success-message]').should('be.visible').and('contain.text', 'Login successful')
  })
})
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsTest runner initialized, browser ready-PASS
2Browser opens and navigates to '/login'Login page is loaded with username, password fields and submit buttonURL contains '/login'PASS
3Find username input using data-cy attribute and type 'testuser'Username input field focused with text 'testuser'Input value equals 'testuser'PASS
4Find password input using data-cy attribute and type 'password123'Password input field focused with text 'password123'Input value equals 'password123'PASS
5Find submit button using data-cy attribute and click itForm submitted, page processing login-PASS
6Find success message using data-cy attribute and verify it is visible and contains 'Login successful'Success message displayed on pageSuccess message is visible and text contains 'Login successful'PASS
Failure Scenario
Failing Condition: Selector does not match any element or element is missing
Execution Trace Quiz - 3 Questions
Test your understanding
Why is using data-cy attributes recommended for selectors in Cypress tests?
AThey select elements by visible text
BThey are automatically generated by Cypress
CThey are stable and do not change with styling or layout changes
DThey are faster than CSS selectors
Key Result
Use custom data attributes like data-cy for selectors to make tests stable and easy to maintain, avoiding selectors tied to styling or layout.