0
0
Cypresstesting~5 mins

cy.siblings() and cy.closest() in Cypress

Choose your learning style9 modes available
Introduction

These commands help you find related elements on a web page. cy.siblings() finds elements next to the current one. cy.closest() finds the nearest parent element that matches a condition.

When you want to check if other items in a list are visible after clicking one item.
When you need to find the container of a button to verify its style or content.
When testing if a selected element has siblings with specific classes or attributes.
When you want to confirm that an element is inside a certain section or form.
When you want to interact with elements near the one you found, like buttons next to a label.
Syntax
Cypress
cy.get(selector).siblings([filter])
cy.get(selector).closest(selector)

cy.siblings() finds all sibling elements of the current element. You can add a filter to narrow down results.

cy.closest() travels up the DOM tree to find the nearest ancestor matching the selector.

Examples
This finds all elements next to '.item' elements at the same level.
Cypress
cy.get('.item').siblings()
// Finds all siblings of elements with class 'item'
This finds siblings of '.item' that also have the class 'active'.
Cypress
cy.get('.item').siblings('.active')
// Finds siblings with class 'active' only
This finds the closest parent form element of the '.button'.
Cypress
cy.get('.button').closest('form')
// Finds the nearest form that contains the button
This helps verify if '#input' is inside a container element.
Cypress
cy.get('#input').closest('.container')
// Finds the nearest ancestor with class 'container'
Sample Program

This test visits a sample page. The first test finds siblings of the active list item and checks there are 3 siblings. The second test finds the closest form of an input and checks it has the expected class.

Cypress
describe('Test siblings and closest commands', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/traversal')
  })

  it('checks siblings of a list item', () => {
    cy.get('.traversal-list > li.active')
      .siblings()
      .should('have.length', 3)
  })

  it('finds closest form of an input', () => {
    cy.get('#inputEmail')
      .closest('form')
      .should('have.class', 'form-horizontal')
  })
})
OutputSuccess
Important Notes

Use cy.siblings() to find elements on the same level in the DOM tree.

Use cy.closest() to find the nearest parent element matching a selector.

Both commands help navigate the page structure to write better tests.

Summary

cy.siblings() finds elements next to the current one.

cy.closest() finds the nearest parent matching a selector.

These commands help you check related elements easily in tests.