I am a newbie to cypress. I have a table of users and each row there is edit button. I want to find particular user by email and click on the edit button in that row. Can you please help me locating edit button for my Cypress test?
4 Answers
It's easier than that.
You can find the right row (<tr>
not <td>
) with .contains()
.
Then just find the <a>
within that row
cy.contains('tr', 'Joei Smithi') // whichever bit of text id's them,
// but specify 'tr' as the element
// Checks all the row children, but returns the row
.find('a') // Now find() looks only in that row, and any depth
.click() // hit it

- 3,530
- 7
- 21
You can use data-* attributes to provide context to your selectors and isolate them from CSS or JS changes.
In your html file:
<a data-cy={uniqueId}>Edit</button>
In your cypress testing file:
cy.get('[data-cy=${uniqueId}]').click()
Why use this?
Adding the data-* attribute to the element gives us a targeted selector that's only used for testing.
The data-* attribute will not change from CSS style or JS behavioral changes, meaning it's not coupled to the behavior or styling of an element.
Additionally, it makes it clear to everyone that this element is used directly by test code.

- 29
- 5
So you can do is something like this. First, get the parent row tr
for the email and then inside that row, get the Edit button and click it.
cy.contains('td', 'joe9.smith@yourdomain.co.nz')
.parent('tr')
.children('td')
.find('a')
.click()

- 17,144
- 3
- 29
- 52
Cay you try the following code,
First we will find out the index of your email
then apply the index in the EDIT button
let position = 0; cy.get('table > tr').should(($eachTr) => { let count = $eachTr.length; for(let i=0; i<count; i++ ){ const text = $eachTr.text(); if(text.includes('your email')){ position = i; } } }); cy.contains('EDIT').eq(position).click();

- 758
- 1
- 5
- 11