← Back to Cypress Mastery
Basic16 min read

Selectors & Queries

Find elements with cy.get, cy.contains, and query chaining best practices.

cy.get()

cy.get selects elements by CSS selector, data attributes, or aliases. Cypress retries get until element exists or defaultCommandTimeout elapses.

Prefer stable selectors: data-cy, data-testid, or semantic attributes over generated CSS classes that change with styling refactors.

cy.get('[data-cy="submit-button"]');
cy.get('input[name="email"]');
cy.get('#login-form');

cy.contains()

Find elements by text content—buttons, labels, headings. Pass tag selector optionally to narrow scope: cy.contains("button", "Save").

Text matchers accept strings or regex. Case sensitivity follows DOM text; use regex flag i for case-insensitive match.

  • Scope with cy.get(".modal").contains("Confirm") to avoid wrong match
  • Partial text match may hit multiple nodes—narrow with parent context
  • Prefer accessible names via cy.findByRole when using Testing Library plugin
cy.contains("Sign in");
cy.contains(/sign in/i);
cy.contains('[role="alert"]', "Invalid password");

Query Chaining

Commands yield DOM elements to subsequent commands within same chain. .find() searches descendants; .filter() narrows sibling set.

Breaking chain with cy.get again re-queries entire document—scope first with get container, then find children for performance and precision.

cy.get('[data-cy="cart"]')
  .find('[data-cy="cart-item"]')
  .should("have.length", 2)
  .first()
  .contains("Remove")
  .click();

Aliases and Within

cy.as("alias") stores subject for later cy.get("@alias"). cy.within limits subsequent commands to descendant tree—useful in modals and tables.

Aliases also work for intercept stubs and fixtures referenced across steps.

cy.get("table").as("ordersTable");
cy.get("@ordersTable").find("tbody tr").should("have.length.gte", 1);

cy.get('[role="dialog"]').within(() => {
  cy.contains("Confirm").click();
});

Selector Best Practices

Collaborate with developers on data-cy conventions. Avoid XPath unless necessary. Do not select by implementation details like React component names.

Review failing CI screenshots—brittle selectors are top flake cause. Prefer user-visible attributes: placeholder, aria-label, associated label text.

  • Document selector strategy in team testing guide
  • Lint against cy.get with overly generic selectors in custom ESLint rules
  • Use .should("exist") before interacting if element appears asynchronously

Get In Touch


Ready to discuss your next project? Drop me a message.