0
0
Cypresstesting~3 mins

Why cy.first(), cy.last(), cy.eq() in Cypress? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could pick exactly the right item on a page every time, without scrolling or guessing?

The Scenario

Imagine you have a long list of items on a webpage, and you want to check just the first, last, or a specific item manually by clicking and inspecting each one.

This means scrolling, clicking, and guessing if you picked the right element every time.

The Problem

Manually finding elements is slow and tiring.

You might click the wrong item or miss changes in the list order.

It's easy to make mistakes and hard to repeat the exact steps consistently.

The Solution

Using cy.first(), cy.last(), and cy.eq() lets you directly pick the first, last, or any specific item in a list automatically.

This saves time, reduces errors, and makes your tests clear and reliable.

Before vs After
Before
cy.get('li').then(items => {
  const first = items[0];
  // manual checks here
})
After
cy.get('li').first().should('be.visible')
What It Enables

You can quickly and confidently test specific elements in a list without guessing or extra steps.

Real Life Example

Testing a shopping cart where you want to check the first product's price, the last product's name, or the third product's quantity easily.

Key Takeaways

Manual element selection is slow and error-prone.

cy.first(), cy.last(), and cy.eq() pick elements directly and reliably.

This makes tests faster, clearer, and less buggy.