0
0
Cypresstesting~15 mins

Why element selection drives interaction in Cypress - Automation Benefits in Action

Choose your learning style9 modes available
Verify interaction with a button using correct element selection
Preconditions (1)
Step 1: Locate the button with the text 'Click Me' using a reliable selector
Step 2: Click the button
Step 3: Verify that a message 'Button clicked!' appears on the page
✅ Expected Result: The message 'Button clicked!' is visible after clicking the button
Automation Requirements - Cypress
Assertions Needed:
Verify the button is found using a reliable selector
Verify the button click triggers the expected message display
Best Practices:
Use semantic selectors like data-cy attributes
Avoid brittle selectors like absolute XPaths
Use Cypress commands consistently (cy.get, cy.contains)
Add assertions to confirm element presence before interaction
Automated Solution
Cypress
describe('Why element selection drives interaction', () => {
  beforeEach(() => {
    cy.visit('/sample-page')
  })

  it('Clicks the button and verifies the message', () => {
    // Use data-cy attribute for reliable selection
    cy.get('[data-cy=click-me-button]').should('be.visible').click()

    // Verify the message appears
    cy.contains('Button clicked!').should('be.visible')
  })
})

The test starts by visiting the sample page before each test to ensure a fresh state.

We select the button using a data-cy attribute, which is a stable and semantic selector that won't break if the UI changes slightly.

We assert the button is visible before clicking to avoid errors if the element is missing or hidden.

After clicking, we verify the expected message appears, confirming the interaction worked as intended.

Common Mistakes - 3 Pitfalls
Using brittle selectors like absolute XPath
{'mistake': 'Not asserting element visibility before interaction', 'why_bad': 'Trying to click a hidden or missing element causes test failures and unclear errors.', 'correct_approach': "Always assert the element is visible using .should('be.visible') before clicking."}
Mixing different selector strategies inconsistently
Bonus Challenge

Now add data-driven testing with 3 different buttons each showing a unique message

Show Hint