Darksymphony
Darksymphony

Reputation: 2693

Cypress iterating through table assert two columns

I have a simple table e.g.:

<table>
<tr>
<td>name 1</td>
<td>name 2</td>
<tr>
<tr>
<td>name 3</td>
<td>name 4</td>
<tr>
</table>

With cypress I want to verify, that name 1 and name 2 are not present in the table (but only if they are next to each). If name 1 is alone in any td, then it is ok, so only if name 1 and name 2 are in one table row.

I tried to iterate through table via:

verifyTable(child, parent) {
    cy.get("table tr").each(($el, index, $list) => {

          cy.get("tr").eq(index).find("td:nth(0)").should('not.contain',child);
          cy.get("tr").eq(index).find("td:nth(1)").should('not.contain',parent);
    
        })
}

This is working fine, but if it finds child in first column, it fails and doesn't check the next column. The same if the element doesn't exists in first column but exists only in second column, it fails.

It should fail only if child and parent exists next to each other. I am not sure how to connect both conditions.

Even if I used chaning with AND, if it finds the first element, it fails:

cy.get("tr").eq(index).should('not.contain',child).and('not.contain',parent);

Upvotes: 1

Views: 1536

Answers (1)

Fody
Fody

Reputation: 32052

You can substitute jQuery expressions when checking the cells, they won't fail the test if not found.

Then test the combination - I think I have the right logic, but you may need to adjust if I misunderstood.

verifyTable(child, parent) {
  cy.get("table tr").each(($tr, index, $list) => {

    const childExists = $tr.find(`td:nth(0):contains(${child})`).length;
    const parentExists = $tr.find(`td:nth(1):contains(${parent})`).length;

    expect(!childExists || !parentExists).to.eq(true)

    // or this is the same, but may be closer to your specified requirement
    expect(!(childExists && parentExists)).to.eq(true)

  })
}

Upvotes: 3

Related Questions