0
0
Cypresstesting~5 mins

cy.prev() and cy.next() in Cypress

Choose your learning style9 modes available
Introduction

These commands help you find elements right before or after another element on a webpage. It makes checking nearby items easy.

You want to check the label just before an input box.
You need to verify the next item in a list after a selected element.
You want to test navigation buttons that appear next to each other.
You want to confirm the previous sibling element has the correct text.
You want to interact with elements that are neighbors in the HTML structure.
Syntax
Cypress
cy.get('selector').prev()
cy.get('selector').next()

cy.prev() finds the immediate previous sibling element.

cy.next() finds the immediate next sibling element.

Examples
This finds the list item just before the one with class 'active'.
Cypress
cy.get('li.active').prev()
This finds the button right after the button with class 'submit'.
Cypress
cy.get('button.submit').next()
This finds the element immediately after the label for 'email'.
Cypress
cy.get('label[for="email"]').next()
Sample Program

This test visits a sample page with breadcrumb navigation. It finds the active breadcrumb item, then checks the text of the previous and next siblings to confirm they are 'Library' and 'Data'.

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

  it('checks previous and next siblings', () => {
    // Find the active list item and check its previous sibling text
    cy.get('.breadcrumb > .active')
      .prev()
      .should('have.text', 'Library')

    // Find the active list item and check its next sibling text
    cy.get('.breadcrumb > .active')
      .next()
      .should('have.text', 'Data')
  })
})
OutputSuccess
Important Notes

If there is no previous or next sibling, the command yields an empty set.

These commands only look at siblings on the same level in the HTML tree.

Summary

cy.prev() gets the element before the current one.

cy.next() gets the element after the current one.

Use them to check or interact with nearby elements easily.