Search code examples
angulartypescriptcypress

In Cypress, can you find the first row in a table that has a specific text?


I'm relatively new to Cypress tests.

I have a table that has more than one row with a specific text, and I only want to get the very first row.

So far the only way I've figured out how to do this is to traverse all of the rows in the table looking for the text. Not only is this kind of ugly, it prevents the test from only acting on the first row it finds.

Here is my kinda kludgy code:

const SELECTOR = {
    dataTableBody: '.p-datatable-tbody'
} as const;


cy.assertVisible(SELECTOR.dataTableBody);
cy.then(() => {
    cy.get(SELECTOR.dataTableBody).then($tbody => {
        cy.get(SELECTOR.dataTableBody).find('tr').each($row => {
            if (($row.find('td:nth-child(1)').text().trim()) === 'MyText') {

                    //I only want it to get here on the FIRST row that has 'MyText'
            }
        });
    });
});

Thanks!


Solution

  • I would use .contains() since you search for some text.

    .contains() always returns just the first element even if there are many matching elements.

    Here is a simple example table

    <table>
      <tbody class="p-datatable-tbody">
        <tr>                   
          <td></td>
          <td>MyText</td>      
        </tr>
        <tr>
          <td>MyText</td>
          <td></td>
        </tr>
      </tbody>
    </table>
    

    This is the simplest command sequence I can think of

    cy.get('.p-datatable-tbody').should('be.visible')
      .contains('tr', 'MyText')
      .then($row => {
        // $row is the first row that contains 'MyText' anywhere in the row
    
        expect($row.index()).to.eq(0)   // 1st row was picked
      })
    

    But it returns the row that has 'MyText' anywhere in the row.

    If you want to check only the first column, specify td:nth-child(1)

    cy.get('.p-datatable-tbody').should('be.visible')
      .contains('td:nth-child(1)', 'MyText')
      .parent()
      .then($row => {
        // $row is the first row that contains 'MyText' in the first column
    
        expect($row.index()).to.eq(2)   // 2nd row was picked
      })