Reputation: 209
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?
Upvotes: 3
Views: 2156
Reputation: 5461
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
Upvotes: 3
Reputation: 18624
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', '[email protected]')
.parent('tr')
.children('td')
.find('a')
.click()
Upvotes: 0
Reputation: 39
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.
source: best practices from official cypress doc
Upvotes: 1
Reputation: 838
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();
Upvotes: 0