DEV Community

Cover image for Cypress tips&tricks: Find Dynamic Table Selectors
keycho47 for Bornfight

Posted on

Cypress tips&tricks: Find Dynamic Table Selectors

In my world, developers can't always make your selector unique or custom just for you to catch them in your cypress test like in Cypress best practice doc.
But there is a trick I use in my tests when I need to catch dynamic table index or row index. This happens when my tests want to select some elements that are the same for all data in table like edit or delete button.
Like in this case ->
image
Edit icon has a dynamic selector so I need to get rowKey to click on a specific row.

My solution:

  1. First make sure you can use cy.contains() method on some unique element. You can do this on creating this data element in your test or make deal with developers to create test data or fixtures with unique ID or some other property.
  2. After catching this element we can use .then() function where magic is happening.

Here is a snippet from my code for example:

cy.contains("Unique Data")
      .should("be.visible")
      .then(($el) => {
        console.log($el);
        let elRowKey = $el[0].parentElement.dataset.rowKey;
        cy.get(
          '[data-row-key="' +
            elRowKey +
            '"] > :nth-child(4) > [data-test=edit-email-template] > .anticon > svg'
        ).click({ force: true });

        cy.get("[data-test=disable-delete-tooltip]").click();
        cy.get("[data-test=confirm-delete-button]").click({ force: true });
      });
Enter fullscreen mode Exit fullscreen mode

In then() function we pass $el which contains all kinds of data so I use console.log() to see and search
a specific data I can use to help myself.
After finding elRowKey in $el properties I simply use cy.get() function to get a specific icon on that row using string concatenation with variable in which I put my rowKey.

This way I always get my rowKey on element I want to delete or edit, I hope I helped with this trick and make sure you comment on the post if you find better solution.

Tnx <3

Top comments (1)

Collapse
 
prasannakumar1 profile image
Prasanna-Kumar-1 • Edited

@keycho47 ....Excellent article. Thanks for sharing this.

Can you please share an example URL where i can practice the above scenario?