0
0
Cypresstesting~15 mins

cy.first(), cy.last(), cy.eq() in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify cy.first(), cy.last(), and cy.eq() commands on a list of items
Preconditions (2)
Step 1: Open the web page with the list of items.
Step 2: Use cy.get() to select all elements with class 'item' inside the 'item-list'.
Step 3: Use cy.first() to get the first item and verify its text is 'Item 1'.
Step 4: Use cy.last() to get the last item and verify its text is 'Item 5'.
Step 5: Use cy.eq(2) to get the third item (index 2) and verify its text is 'Item 3'.
✅ Expected Result: The first item text is 'Item 1', the last item text is 'Item 5', and the third item text is 'Item 3'. All assertions pass.
Automation Requirements - Cypress
Assertions Needed:
Verify the text of the first item is 'Item 1'.
Verify the text of the last item is 'Item 5'.
Verify the text of the third item (index 2) is 'Item 3'.
Best Practices:
Use cy.get() with a clear and specific CSS selector.
Use cy.first(), cy.last(), and cy.eq() to select elements by position.
Use should('have.text', expectedText) for assertions.
Avoid hardcoding selectors that are brittle.
Use descriptive test names.
Automated Solution
Cypress
describe('Test cy.first(), cy.last(), and cy.eq() commands', () => {
  beforeEach(() => {
    cy.visit('/items-page')
  })

  it('should verify first, last, and eq selectors on item list', () => {
    cy.get('.item-list .item').first().should('have.text', 'Item 1')
    cy.get('.item-list .item').last().should('have.text', 'Item 5')
    cy.get('.item-list .item').eq(2).should('have.text', 'Item 3')
  })
})

This test suite visits the page with the list of items before each test.

The test uses cy.get() to select all items with the class item inside the container item-list.

Then it uses cy.first() to get the first item and asserts its text is 'Item 1'. Similarly, cy.last() gets the last item and asserts its text is 'Item 5'. Finally, cy.eq(2) selects the third item (index 2) and asserts its text is 'Item 3'.

Assertions use should('have.text', ...) to check the exact text content.

This approach is clear, uses best practices, and the selectors are specific and maintainable.

Common Mistakes - 4 Pitfalls
Using cy.get() multiple times for the same selector instead of chaining
Using hardcoded XPath selectors instead of CSS selectors
Using .eq() with an out-of-range index
{'mistake': "Using .should('contain', text) instead of .should('have.text', text) for exact match", 'why_bad': 'Contain checks partial text and may pass incorrectly.', 'correct_approach': "Use .should('have.text', text) to assert exact text content."}
Bonus Challenge

Now add data-driven testing to verify first, last, and eq(2) items for 3 different lists with different item texts.

Show Hint