Deleting rows from a table after testing, generic function

Viewed 19

I have some tests on an HTML table which add, modify, delete. I'd like a generic function I can apply to clean up previous data to start clean each time.

I currently reset the page, but there's quite a few steps to take to get to the start of testing so an "undo" function would be very useful WRT faster tests.

This is currently what I have (simplified) for a single row

cy.get('tr').should('have.length', 3).eq(0).click()
cy.get('tr').should('have.length', 2)

Now I need to enhance it to handle any number of rows. I tried looping but it didn't work - the test seems to run too fast for the page to keep up, if that makes sense?

1 Answers

To delete rows from a table is tricky if the DOM gets re-written each time you delete.

At minimum use a .should() assertion on the number of rows after each delete, to ensure each step is complete before the next one.

To be really safe, use a recursive function which controls the process, for example

const clearTable = (attempt = 0) => {
  if (attempt === 100) throw 'Too many attempts'     // guards against too many steps

  cy.get('tbody').then($tbody => {
    if($tbody.find('tr').length === 0 ) return;      // exit condition tested here

    cy.get('tr').then($rows => {
      cy.wrap($rows).first().click()                 // action to delete

      cy.then(() => {
        clearTable(++attempt)                        // next step queued using then()
      })
    })
  })
}

clearTable()
Related