0
0
Cypresstesting~3 mins

Why Best practices for selectors in Cypress? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a tiny change in choosing selectors can save hours of test failures!

The Scenario

Imagine you are testing a website by clicking buttons and filling forms manually. You try to find elements by guessing their names or looking at their colors. Sometimes you pick the wrong button or miss a field because it looks similar to another.

The Problem

Manually picking elements by their look or random attributes is slow and full of mistakes. If the website changes colors or layout, your guesses break. You waste time fixing tests that fail for no real reason.

The Solution

Using best practices for selectors means choosing stable, clear ways to find elements, like unique IDs or data attributes. This makes tests reliable and easy to maintain, even if the page design changes.

Before vs After
Before
cy.get('.btn-primary').click()
After
cy.get('[data-cy="submit-button"]').click()
What It Enables

It enables writing tests that keep working smoothly as the website grows and changes, saving time and frustration.

Real Life Example

For example, a shopping site uses data attributes like data-cy='add-to-cart' on buttons. Testers can click the right button every time, even if the style or position changes.

Key Takeaways

Manual element picking is slow and error-prone.

Best selectors use stable, unique attributes like data-cy.

Good selectors make tests reliable and easy to update.