Cypress 05 ๐ฒ Selectors โ cy.get, cy.contains, and data-cy Attributes
Cypress selectors are cy commands that find elements and return a chain for further commands. The two core selectors are cy.get(), which finds by CSS selector, and cy.contains(), which finds by text content. The recommended attribute for test-specific selectors is data-cy, which is stable across class-name and markup refactors and is scoped to the test rather than the styling. The choice of selector determines whether a test survives a redesign, and whether it fails with a clear “element not found” message or a confusing “clicked the wrong element” one.
This chapter covers the two selectors, the data-cy attribute convention, and the selector strategies that balance stability against accessibility. The sections that follow walk through cy.get, cy.contains, and the attribute patterns that keep tests resilient.
Key point: cy.get(selector) finds by CSS and retries until the element exists; cy.contains(text) finds the first element containing the text; data-cy is the recommended test attribute because it is stable, scoped to tests, and does not leak into styling.
a. cy.get and CSS selectors
cy.get(selector) takes a CSS selector and returns a chain for the first matching element (or all matching elements if .should('have.length') is used). The command retries until at least one element matches or the timeout expires. The selector can be an id (#email), a class (.btn), an attribute ([data-cy="submit"]), a tag (button), or a combination.
// By id
cy.get("#email").type("user@example.com");
// By class (discouraged; classes change with styling)
cy.get(".login-form").should("be.visible");
// By attribute (recommended for tests)
cy.get('[data-cy="submit"]').click();
// By tag and attribute
cy.get('button[type="submit"]').click();
// Multiple elements
cy.get("li").should("have.length", 3);
// Scoped within a parent
cy.get('[data-cy="user-list"]').find("li").should("have.length", 3);
The cy.get command is scoped to the document by default. To find an element inside a previously selected element, use .find() on the chain, not a second cy.get. The .find() searches within the subject of the previous command; cy.get searches the whole document.
// Scoped: find li inside the user list
cy.get('[data-cy="user-list"]').find("li").first().click();
// Not scoped: finds any li in the document
cy.get("li").first().click();
The .within() command is the block form of scoping. It runs a callback with the previous subject as the scope, so every cy.get inside it searches only within that element.
cy.get('[data-cy="login-form"]').within(() => {
cy.get('[data-cy="email"]').type("a@b.com");
cy.get('[data-cy="submit"]').click();
});
b. cy.contains and text matching
cy.contains(text) finds the first element in the document that contains the text. It accepts a string (substring match, case-sensitive by default) or a regular expression. The optional first argument is a selector that scopes the search.
// Find the first element containing "Welcome"
cy.contains("Welcome").should("be.visible");
// Scope to a selector
cy.contains("button", "Submit").click();
// Regex match
cy.contains(/Welcome, \w+/).should("be.visible");
// Chain to interact
cy.contains("a", "Forgot password?").click();
cy.contains is useful for text-driven assertions and for clicking elements whose text is the primary identifier. It returns the deepest element that contains the text, which is usually the element the user would click, but not alwaysโa <span> inside a <button> is the deepest element containing the text, and clicking the span may not trigger the button’s handler.
The cy.contains("button", "Submit") form is the safer pattern for interactive elements: it scopes the text search to button elements, so it finds the button rather than its inner span.
// Safer: scope to the element type
cy.contains("button", "Submit").click();
// Less safe: may click an inner span
cy.contains("Submit").click();
c. data-cy and the test attribute convention
Cypress recommends the data-cy attribute for selectors that exist solely for testing. The attribute is not used by CSS or JavaScript, so it does not change when the styling changes, and it does not leak into the production behavior. The convention is documented in the Cypress best practices and is supported by the cypress-selectors plugin and the data-cy ESLint rule .
<button data-cy="submit">Place order</button>
cy.get('[data-cy="submit"]').click();
The attribute name is configurable with testIdAttribute (or cypress-selector-playground), but data-cy is the default in the Cypress ecosystem. The data-test, data-testid, and data-qa variants are used by other tools; the project should choose one and apply it consistently.
The data-cy attribute is stable but not accessible. A test that uses data-cy verifies the behavior but not the accessibility; a screen reader does not read data-cy, so a button with a data-cy and no accessible name passes the test and fails the user. The Cypress documentation recommends using the attribute in combination with the role-based queries where accessibility matters, but Cypress itself does not have Playwright’s getByRole โ the cypress-testing-library plugin provides it.
The ESLint rule eslint-plugin-cypress includes a no-unnecessary-waiting rule and a data-cy convention; the cypress-selectors plugin adds a data-cy helper. The choice of attribute is a convention, not a technical requirement, but the convention is what keeps the selectors consistent across the suite.
Complete Example Session
<!-- ============================================
PART 1: THE MARKUP
============================================ -->
<form data-cy="login-form">
<label for="email">Email</label>
<input id="email" data-cy="email" type="email" />
<label for="password">Password</label>
<input id="password" data-cy="password" type="password" />
<button type="submit" data-cy="submit">Sign in</button>
</form>
<ul data-cy="user-list">
<li>Ana</li>
<li>Ben</li>
<li>Cleo</li>
</ul>
// ============================================
// PART 2: cy.get WITH data-cy
// ============================================
describe("login form", () => {
it("fills and submits", () => {
cy.visit("/login");
cy.get('[data-cy="email"]').type("user@example.com");
cy.get('[data-cy="password"]').type("password123");
cy.get('[data-cy="submit"]').click();
cy.url().should("include", "/dashboard");
});
});
// ============================================
// PART 3: SCOPED SELECTORS
// ============================================
describe("user list", () => {
it("has three users", () => {
cy.visit("/users");
// Scoped to the list, not the whole document
cy.get('[data-cy="user-list"]')
.find("li")
.should("have.length", 3);
});
});
// ============================================
// PART 4: cy.contains FOR TEXT
// ============================================
describe("navigation", () => {
it("clicks the forgot password link", () => {
cy.visit("/login");
cy.contains("a", "Forgot password?").click();
cy.url().should("include", "/reset");
});
});
// ============================================
// PART 5: within() FOR BLOCK SCOPING
// ============================================
describe("within", () => {
it("fills the form within its scope", () => {
cy.visit("/login");
cy.get('[data-cy="login-form"]').within(() => {
cy.get('[data-cy="email"]').type("a@b.com");
cy.get('[data-cy="submit"]').click();
});
});
});
The parts covered the markup with data-cy, cy.get with the attribute, scoped .find(), cy.contains with a selector, and .within() block scoping.
Quick Reference
Selectors
| Command | Matches | Retry |
|---|---|---|
cy.get(selector) | CSS selector | Yes |
cy.contains(text) | First element containing text | Yes |
cy.contains(selector, text) | Scoped text match | Yes |
.find(selector) | Descendant of previous subject | Yes |
.within(fn) | Block scope | N/A |
Selector Strategies
| Strategy | Stability | Accessibility |
|---|---|---|
data-cy | High | None |
id | Medium | None |
aria-label | Medium | High |
| Text content | Medium | High |
| CSS class | Low | None |
data-cy Convention
| Item | Detail |
|---|---|
| Attribute | data-cy |
| Purpose | Test-only selector hook |
| Alternatives | data-test, data-testid, data-qa |
| Scope | Tests only, not styling |
Best Practices
โ Do This:
// Use data-cy for test selectors
cy.get('[data-cy="submit"]').click(); // โ
// Scope within a parent
cy.get('[data-cy="form"]').find('[data-cy="email"]'); // โ
// Scope text to an element type
cy.contains("button", "Submit").click(); // โ
// Use within for blocks
cy.get('[data-cy="form"]').within(() => { ... }); // โ
โ Don’t Do This:
// Use CSS classes tied to styling
cy.get(".btn-primary").click(); // โ
// Use cy.get for scoped search
cy.get('[data-cy="list"]'); cy.get("li"); // not scoped // โ
// Click on text without scoping
cy.contains("Submit").click(); // may click a span // โ
// Rely on data-cy for accessibility
// (screen readers do not read it) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Selector breaks on redesign | CSS class used | Use data-cy |
| Scoped search finds wrong element | cy.get instead of .find | Scope with .find or .within |
| Click does nothing | Text matched inner span | Scope to element type |
| Multiple matches | Selector too broad | Add attribute or scope |
Real-World Examples
1. cy.get by attribute
cy.get('[data-cy="email"]').type("a@b.com");
2. cy.get by id
cy.get("#email").type("a@b.com");
3. cy.contains with selector
cy.contains("button", "Submit").click();
4. cy.contains with regex
cy.contains(/Welcome, \w+/).should("be.visible");
5. .find scoped
cy.get('[data-cy="list"]').find("li").should("have.length", 3);
6. .within block
cy.get('[data-cy="form"]').within(() => { ... });
7. data-cy on an input
<input data-cy="email" />
8. data-cy on a button
<button data-cy="submit">Submit</button>
9. Custom attribute
// config: e2e: { testIdAttribute: "data-test" }
10. ESLint rule
eslint-plugin-cypress enforces data-cy convention
Visual
cy.get vs cy.contains
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cy.get('[data-cy="submit"]') โ
โ โ finds by CSS attribute โ
โ โ retries until the element exists โ
โ โ
โ cy.contains("button", "Submit") โ
โ โ finds by text content, scoped to button โ
โ โ retries until an element contains the text โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Scoping
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DOCUMENT โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ [data-cy="user-list"] โ โ
โ โ <li>Ana</li> โโโ .find("li") โ โ
โ โ <li>Ben</li> โ โ
โ โ <li>Cleo</li> โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ cy.get('[data-cy="user-list"]').find("li") โ
โ searches only inside the list โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Selector Stability
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HIGH STABILITY โ
โ data-cy="submit" โ
โ โ โ
โ โผ โ
โ survives class rename, markup refactor, redesign โ
โ โ
โ LOW STABILITY โ
โ .btn-primary > span โ
โ โ โ
โ โผ โ
โ breaks when the class changes or a wrapper is added โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
data-cy and Accessibility
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ data-cy="submit" โ
โ โ โ
โ โโโโบ test finds the element โ
โ โ โ
โ โโโโบ screen reader does NOT read it โ
โ โ
โ The test verifies behavior, not accessibility. โ
โ Use accessible names alongside data-cy when needed. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| CSS selector | cy.get(selector) |
| Text selector | cy.contains(text) |
| Scoped text | cy.contains(selector, text) |
| Descendant | .find(selector) |
| Block scope | .within(fn) |
| Test attribute | data-cy |
| Retry | Built into cy.get and cy.contains |
Key takeaways:
cy.getfinds by CSS and retries until the element exists. The selector can be an id, an attribute, a class, or a tag, and the choice determines whether the test survives a redesign .cy.containsfinds by text, scoped to a selector when needed. The scoped formcy.contains("button", "Submit")is safer for interactive elements because it finds the button rather than an inner span.data-cyis the recommended test attribute. It is stable across styling changes and scoped to tests, but it does not verify accessibility. The test should use accessible names alongside it when accessibility matters..findand.withinscope the search.cy.getsearches the whole document;.findsearches within the previous subject;.withinruns a block of commands scoped to an element.- CSS classes are the least stable selector. A class tied to styling changes when the design changes, which makes the test fail for a reason unrelated to the behavior.
Remember: A selector is how the test finds the element, and the choice of selector determines whether the test is resilient to refactors. Use data-cy for test-specific hooks, scope with .find and .within to avoid matching the wrong element, and use cy.contains with a selector for text-driven interactions. The attribute is stable but not accessible; the test verifies behavior, and the accessible name is a separate concern.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!