In Cypress how to count the number of rows in a table?

2.1k views Asked by At

I am doing E2E tests with cypress. i have to count the number of rows in a table which are different from case to case.

in normal javascript I just write this to get the number of total rows of the column

document.getElementById('hometable').getElementsByTagName("tr").length-1

unfortunately in cypress i get the following error:

 document.getElementById('hometable').getElementsByTagName("tr").length-1

VM298:1 Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
    at <anonymous>:1:38
(anonymous) @ VM298:1

I tried to count like this but got nothing

cy.get('hometable').find('tr').each(function(row, i){
        expect(i)
})

$Chainer {userInvocationStack: "", specWindow: Window, chainerId: "chainer99", firstCall: false, useInitialStack: false}
chainerId: "chainer99"
firstCall: false
specWindow: Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
useInitialStack: false
userInvocationStack: ""
__proto__: Object

i can't figure out where it returns me the number of rows

1

There are 1 answers

0
Alapan Das On

I think your approach is correct, You can use the each(). There is one more parameter that you can add to each, list and this will give you the count for the number of rows. You can check the cypress document for each(). Make sure the locator is correct.

cy.get('#hometable > tr').each(function(row, i, list) {}).then(function(list) {
      //list will give you the count of tr
    }