Search code examples
indexinggetrowcypress

Cypress get index row that contain the element I have with the given data attribute


I have a mat-table with

  <mat-row>
        <mat-cell>Firstname</mat-cell>
        <mat-cell>Lastname</mat-cell> 
        <mat-cell>Age</mat-cell>
      </mat-row>
      <mat-row>
        <mat-cell>Jill</mat-cell>
        <mat-cell>Smith</mat-cell> 
        <mat-cell> <mat-icon data-mat-icon-name="pinned"> </mat-cell>
      </mat-row>

And I need to know the row index of the element that has data-mat-icon-name='pinned'

I tried the below code:

   cy.get("mat-table").find("[data-mat-icon-name='pinned']").invoke("index").then((i) => {
      cy.log(i); // prints 0. Should print 1
    });

But gives me index 0. Should give index 1.

So maybe is just giving some index of the cell and not of the row?

Any idea how I can get the row index?

Do. I need to use cy.parent ?

Edit:

If I do cy.get("mat-table").find("[data-mat-icon-name='pinned']").should("exist");

The element exits in the Dom


Solution

  • From the jQuery docs .index()

    If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

    But the <mat-icon> you find is by itself in the cell.

    You need to navigate to the parent row and find it's index among siblings,

    cy.get('mat-table')
      .find('[data-mat-icon-name=pinned]')
      .parents('mat-row')
      .invoke('index')
      .then((i) => {
        cy.log(i); // prints 1
      });