</>

Technology

Cypress

Difficulty

Beginner

Interview Question

How do you select elements in Cypress? Explain cy.get() and cy.contains().

Answer

Element Selection in Cypress

cy.get() — Select by CSS Selector

JavaScript
// By ID
cy.get('#username')

// By class
cy.get('.btn-primary')

// By attribute (recommended)
cy.get('[data-testid="login-btn"]')
cy.get('[data-cy="submit"]')
cy.get('[placeholder="Enter email"]')
cy.get('[type="submit"]')

// By tag
cy.get('button')
cy.get('input')

// Chained (child elements)
cy.get('.form').get('input[type="email"]')
cy.get('table').find('tr').first()

// By index (0-based)
cy.get('li').eq(0)   // first item
cy.get('li').eq(-1)  // last item
cy.get('li').first()
cy.get('li').last()

cy.contains() — Select by Text

JavaScript
// Find element containing this text
cy.contains('Login')
cy.contains('Submit')
cy.contains('Welcome back, Alice')

// Scope to a specific element type
cy.contains('button', 'Login')    // button containing "Login"
cy.contains('td', 'Alice')        // table cell containing "Alice"

// With regex
cy.contains(/login/i)  // case-insensitive
cy.contains(/^\d+ results$/)  // "12 results"

// Chained
cy.get('.nav').contains('Home').click()

Recommended: data-testid Attributes

JavaScript
// Best practice — use data-testid in your HTML
// <button data-testid="submit-btn">Submit</button>

cy.get('[data-testid="submit-btn"]').click()

// Avoid fragile selectors like:
cy.get('.btn.btn-primary.large')   // breaks if CSS class changes
cy.get('div > div:nth-child(3)')   // breaks if DOM order changes

cy.find() — Search Within a Scoped Element

JavaScript
// Find within a parent
cy.get('.user-card').find('[data-testid="name"]')
cy.get('form').find('input').first()
cy.get('table tbody').find('tr').should('have.length', 10)

Real-World Examples

JavaScript
describe('Shopping Cart', () => {
  it('should add product to cart', () => {
    cy.visit('/products');

    // Select first product card's "Add to Cart" button
    cy.get('[data-testid="product-card"]')
      .first()
      .find('[data-testid="add-to-cart"]')
      .click();

    // Verify cart count updated
    cy.get('[data-testid="cart-count"]').should('contain', '1');
  });

  it('should find product by name', () => {
    cy.visit('/products');
    cy.contains('[data-testid="product-name"]', 'Laptop').click();
    cy.url().should('include', '/products/laptop');
  });
});

Follow AutomateQA

Related Topics