0

Please help me find a way to count only non-empty table rows. I tried to use it:

cy.get("#TableId")
    .find("tr")
    .then((rows) => {
        rows.toArray().forEach((element) => {
        if (element.innerHTML.should('be.not.empty')) {
        //rows.index(element) will give you the row index
           cy.log(rows.index(element));
        }
       });
     });

but it throws an error

2 Answers2

6

It depends on what you are aiming for.

Here's an experiment that uses various expressions, you can pick one that suits your requirements.

Don't forget the add tbody to the table selector, since you want to exclude the header row.

Test HTML

<table>
  <tbody>
    <tr>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td><span></span></td>
      <td></td>
    </tr>
    <tr>
      <td>some-text</td>
      <td></td>
    </tr>
    <tr>
      <td>some-text</td>
      <td>another-text</td>
    </tr>
  </tbody>
</table>

Test code

cy.get('table tbody tr')
  .each((tr, index) => {

    console.group('row', index, tr.html().replaceAll('\n', ''))

    const expressions = [
      "tr.html()", 
      "tr[0].innerHTML", 
      "tr.find('td').toArray().map(td => td.innerHTML).join('')",
      "tr.text()",
      "tr.text().trim().replaceAll('\\n', '')",
    ]
    const results = expressions.reduce((acc,e) => {
      acc[e] = eval(e)
      return acc
    }, {})
    console.table(results)
    console.groupEnd()
  })

Output

enter image description here

user16695029
  • 3,365
  • 5
  • 21
-1

.should() and .includes() are Cypress validation functions, and should not be used to determine branching. Instead, you can check the .length of innerText directly to determine your code path. (Chai's .empty assertion, when run on a String, checks if the length of the variable is 0)

cy.get("#TableId")
    .find("tr")
    .then((rows) => {
        rows.toArray().forEach((element) => {
        if (element.innerHTML.length !== 0) { // may need to use `element.text()` instead of `element.innerHTML`
           cy.log(rows.index(element));
        }
       });
     });
agoff
  • 5,818
  • 1
  • 7
  • 20
  • length !== 0 for some reason does not filter lines, both empty and non-empty lines are output to the log. Perhaps the length is not zero because the cypress counts the cells – Corica Vento Mar 17 '23 at 15:09
  • `.length !== 0` may not be the evaluation you want to make, but I was translating your `.should('not.be.empty')` into the same logic that Chai applies for `.be.empty`. Something like `element.innerHTML !== ""` or `element.text().length !== 0` may be the proper solutions, but without an example HTML, I can't really give any exact guidance. – agoff Mar 17 '23 at 18:09