ChinS
ChinS

Reputation: 209

How to find button element in a table grid

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?

enter image description here

Upvotes: 3

Views: 2156

Answers (4)

Paolo
Paolo

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

Alapan Das
Alapan Das

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

Gia
Gia

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

Jayanth Bala
Jayanth Bala

Reputation: 838

Cay you try the following code,

  1. First we will find out the index of your email

  2. 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

Related Questions