0
0
Cypresstesting~10 mins

cy.siblings() and cy.closest() in Cypress - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that when clicking the first list item, the test can find its sibling items and the closest parent list element. It verifies that cy.siblings() correctly finds sibling elements and cy.closest() finds the nearest ancestor element.

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

  it('finds siblings and closest parent', () => {
    // Find the first list item and click it
    cy.get('.traversal-list > li').first().click()

    // From the first list item, get its sibling list items
    cy.get('.traversal-list > li').first()
      .siblings('li')
      .should('have.length.greaterThan', 0)

    // From the first list item, find the closest ul parent
    cy.get('.traversal-list > li').first()
      .closest('ul')
      .should('have.class', 'traversal-list')
  })
})
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsCypress test runner initialized-PASS
2Browser opens and navigates to 'https://example.cypress.io/commands/traversal'Page with traversal commands loaded, showing a list with buttonsPage loaded successfullyPASS
3Find the first list item in '.traversal-list' and click itFirst list item is focused and clickedList item click performedPASS
4From the same list item, find sibling list items using cy.siblings('li')Sibling list items of the first list item are locatedAssert that siblings length is greater than 0PASS
5From the list item, find the closest 'ul' ancestor using cy.closest('ul')Closest ul element with class 'traversal-list' is foundAssert that closest ul has class 'traversal-list'PASS
Failure Scenario
Failing Condition: If the first list item in '.traversal-list' is not found or has no siblings, or closest ul is missing
Execution Trace Quiz - 3 Questions
Test your understanding
What does cy.siblings('li') do in this test?
AFinds the closest parent li element
BFinds all li elements that share the same parent as the current li
CFinds all child li inside the current li
DFinds the next li element in the DOM
Key Result
Use cy.siblings() to find elements sharing the same parent and cy.closest() to find the nearest ancestor element. This helps test relationships in the page structure clearly.