0
0
Cypresstesting~15 mins

cy.siblings() and cy.closest() in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify siblings and closest ancestor elements using Cypress
Preconditions (3)
Step 1: Locate the list item with class 'active'
Step 2: Use cy.siblings() to get all sibling items of the active item
Step 3: Verify that the siblings do not have the 'active' class
Step 4: Use cy.closest() on the active item to find the container with id 'list-container'
Step 5: Verify that the closest container has the correct id
✅ Expected Result: The siblings of the active item are found and none have the 'active' class. The closest container element with id 'list-container' is correctly identified.
Automation Requirements - Cypress
Assertions Needed:
Siblings of the active item do not have 'active' class
Closest container element has id 'list-container'
Best Practices:
Use cy.get() with clear selectors
Chain commands properly
Use assertions with should()
Avoid hardcoded waits, rely on Cypress automatic waits
Automated Solution
Cypress
describe('Test cy.siblings() and cy.closest()', () => {
  beforeEach(() => {
    cy.visit('/test-page') // Replace with actual URL or path
  })

  it('should verify siblings and closest container', () => {
    // Locate the active item
    cy.get('.item.active')
      .as('activeItem')

    // Verify siblings do not have 'active' class
    cy.get('@activeItem')
      .siblings('.item')
      .should('not.have.class', 'active')

    // Verify closest container has id 'list-container'
    cy.get('@activeItem')
      .closest('#list-container')
      .should('have.id', 'list-container')
  })
})

The test starts by visiting the target page.

We locate the active list item using cy.get('.item.active') and save it as an alias @activeItem for reuse.

Using cy.siblings(), we get all sibling elements with class item and assert none have the active class.

Then, we use cy.closest() on the active item to find the nearest ancestor with id list-container and assert it has the correct id.

This approach uses clear selectors, chaining, and Cypress best practices for reliable and readable tests.

Common Mistakes - 3 Pitfalls
Using cy.get() again inside siblings() instead of chaining
Using hardcoded waits like cy.wait(1000) before assertions
Using incorrect selectors that do not match the actual elements
Bonus Challenge

Now add data-driven testing to verify siblings and closest container for three different active items with different classes.

Show Hint