0
0
Cypresstesting~15 mins

Chaining selectors in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify user can select a nested element using chained selectors
Preconditions (3)
Step 1: Open the sample page URL
Step 2: Find the <div> element with class 'container'
Step 3: Within that container, find the <ul> element
Step 4: Within the <ul>, find the first <li> element with class 'item'
Step 5: Click on that <li> element
Step 6: Verify that the clicked <li> element has the class 'selected'
✅ Expected Result: The first <li> item inside the container's <ul> is clicked and has the class 'selected' applied
Automation Requirements - Cypress
Assertions Needed:
Verify the <li> element has class 'selected' after click
Best Practices:
Use chaining of selectors with cy.get().find()
Use .first() to select the first matching element
Use assertions with .should()
Avoid using brittle selectors like absolute XPaths
Use descriptive class selectors
Automated Solution
Cypress
describe('Chaining selectors test', () => {
  it('should click the first list item inside container and verify selection', () => {
    cy.visit('https://example.com/sample-page')
    cy.get('div.container')
      .find('ul')
      .find('li.item')
      .first()
      .click()
      .should('have.class', 'selected')
  })
})

This test opens the sample page URL first using cy.visit(). Then it uses cy.get('div.container') to find the container div. Next, it chains .find('ul') to locate the unordered list inside that container. Then it chains .find('li.item') to get all list items with class 'item' inside the

    . Using .first() selects the first such
  • . The test clicks that
  • and asserts it has the class 'selected' using .should('have.class', 'selected'). This chaining ensures we only look inside the container and list, making the selector precise and maintainable.

Common Mistakes - 4 Pitfalls
Using multiple separate cy.get() calls without chaining
Using absolute XPath selectors
Not using .first() when multiple elements match
Not asserting the expected class after click
Bonus Challenge

Now add data-driven testing to click the first <li> item inside containers with different classes: 'container', 'container-alt', and 'container-special'. Verify each clicked item has class 'selected'.

Show Hint