Position-based selectors cause a bug that is worse than a failing test. Here it is.
Fern Market is an invented plant shop. A test adds Snake Plant to the basket. Snake Plant is the first card on the page, so the test uses its position:
cy.get('.plant-card:nth-child(1) button').click();
The test then checks that the basket shows 1. It works for months. Then someone adds a "Featured" plant to the top of the page. The test still passes. It was adding the wrong plant to the basket, and the test could not tell the difference.
That is the worst thing a test can do. Not fail. Pass while being wrong.
nth-child(1) means "the first one in the list". It describes where the element sits. Positions change whenever someone edits the page.
Instead, use a selector that describes what the element is. A test id is an attribute the developers add to the app on purpose, just for testing. Here is one card in the shop's HTML:
<li data-testid="plant-card">
<h3>Snake Plant</h3>
<button data-testid="add-to-basket">Add to basket</button>
</li>
Nobody moves a test id or renames it by accident, because it exists for one reason.
There is a trap here. Every card has the same add-to-basket button. So cy.get('[data-testid="add-to-basket"]') finds all of them. You might add .first() to pick one. That is a position again. It clicks whichever card is on top, which is the same bug in new words.
What makes this card different from the others is the plant's name. So find the card by its name, then the button inside it:
cy.contains('[data-testid="plant-card"]', 'Snake Plant')
.find('[data-testid="add-to-basket"]')
.click();
Let's read it line by line:
cy.contains(selector, text)finds the element that matches the selector and contains the text. Here that is the one card with "Snake Plant" in it..find(...)searches only inside that card. Buttons in other cards are never considered..click()clicks the button Cypress found.
Now the order of the cards does not matter. A new plant at the top changes nothing. If Snake Plant is removed, the test fails, and that is correct.
You can also find a single button by the text a user reads:
cy.contains('button', 'Checkout').click();
This is good for buttons and links that appear once on the page. When several match, cy.contains takes the first one, so it has the same trap as .first(). If someone changes the wording, your test will fail. Usually that is correct, because the wording is part of what users see.
What to avoid: long CSS paths like div > div:nth-child(2) > span, and class names from your styling framework like .MuiButton-root-2891. Those class names are generated and change between builds.
Remember this: if your selector would break when someone reorders the page, it is the wrong selector.
Reference: Best Practices: Selecting Elements.