0
0
Cypresstesting~15 mins

cy.prev() and cy.next() in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify navigation to previous and next sibling elements using cy.prev() and cy.next()
Preconditions (2)
Step 1: Open the web page with the list
Step 2: Locate the list item with text 'Item 2'
Step 3: Use cy.prev() to get the previous sibling element
Step 4: Verify the previous sibling's text is 'Item 1'
Step 5: Use cy.next() to get the next sibling element
Step 6: Verify the next sibling's text is 'Item 3'
✅ Expected Result: The test should confirm that the previous sibling of 'Item 2' is 'Item 1' and the next sibling is 'Item 3', passing all assertions.
Automation Requirements - Cypress
Assertions Needed:
Assert that the previous sibling's text equals 'Item 1'
Assert that the next sibling's text equals 'Item 3'
Best Practices:
Use cy.contains() to locate elements by text
Chain cy.prev() and cy.next() correctly
Use should() assertions for verifying text content
Avoid hardcoded selectors; prefer text-based selectors for clarity
Automated Solution
Cypress
describe('Test cy.prev() and cy.next() commands', () => {
  beforeEach(() => {
    cy.visit('/list-page') // Replace with actual URL or path
  })

  it('should verify previous and next siblings of Item 2', () => {
    cy.contains('li', 'Item 2')
      .prev()
      .should('have.text', 'Item 1')

    cy.contains('li', 'Item 2')
      .next()
      .should('have.text', 'Item 3')
  })
})

This test suite visits the page containing the list before each test.

The test locates the list item with text 'Item 2' using cy.contains('li', 'Item 2').

Then it uses .prev() to get the previous sibling and asserts its text is 'Item 1' with .should('have.text', 'Item 1').

Similarly, it uses .next() to get the next sibling and asserts its text is 'Item 3'.

This approach uses clear selectors and Cypress chaining for readability and reliability.

Common Mistakes - 3 Pitfalls
{'mistake': 'Using cy.get() with a generic selector instead of cy.contains() to find the specific list item', 'why_bad': 'Generic selectors may select multiple elements, causing the test to fail or behave unpredictably.', 'correct_approach': "Use cy.contains('li', 'Item 2') to precisely locate the list item by its text."}
Not chaining .prev() or .next() directly after locating the element
{'mistake': "Using .text() instead of .should('have.text', ...)", 'why_bad': ".text() is not a Cypress command and will cause errors; assertions must use Cypress's should() syntax.", 'correct_approach': "Use .should('have.text', 'expected text') to assert element text content."}
Bonus Challenge

Now add data-driven testing to verify previous and next siblings for 'Item 3' and 'Item 4' as well.

Show Hint