javascripttestingcypress

Cypress Test . How to test if a value (here title) is in the right category?


Cypress Test.

The "category name" and the "title name" is in the same column of a table.

I know how to find the fitting "value" to a "title" of the same row but inside a column I have not found yet a solution.

This is the example to find a value fitting to an another value of the same row:

cy.get('.table1 > tbody > tr:nth-child(2) > td:nth-child(1)').each(($e1, index, $list) => {
        var titeltext=$e1.text()
        if(titeltext.includes('title 1')) {
            cy.get('.table1 > tbody > tr:nth-child(2) > td:nth-child(3)').eq(index).then(function(aValue) {
                var theValue = aValue.text()
                expect (theValue.trim()).to.equal('value1')
            })
        }
    })

But to find a value (here "title") being in the right category I have no idea so far. Is there cypress command like a "next value after a specific and fix entry in the same column"?

The table would be like this:

enter image description here

Code:

<table border="1">
<tr>
    <td>category 1</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>
<tr>
    <td>title 1</td>
    <td>subtitle 1</td>
    <td>value 1</td>
</tr>
<tr>
    <td>category 2</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>
<tr>
    <td>title 2</td>
    <td>subtitle 2</td>
    <td>value 2</td>
</tr>
<tr>
    <td>title 3</td>
    <td>subtitle 3</td>
    <td>value 3</td>
</tr>
<tr>
    <td>category 3</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>
<tr>
    <td>title 1</td>
    <td>&nbsp;</td>
    <td>value 4</td>
</tr>
<tr>
    <td>title 4</td>
    <td>subtitle 4</td>
    <td>value 5</td>
</tr>
<tr>
    <td>category 4</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>
<tr>
    <td>title 5</td>
    <td>&nbsp;</td>
    <td>value 6</td>
</tr>

How to test for example that in the same column "title 2" is in the "category 2"?

Thank you very much!


Solution

  • The commands .parent() and .prev() take you to the row and then previous row.

    You don't need an .each() because you specify exactly one row and column with tr:nth-child(2) > td:nth-child(1).

    To find category for "title 2" / "value 2"

    cy.get('.table1 > tbody > tr:nth-child(4) > td:nth-child(1)')
      .should('contain', 'title 2')                            // row 4 col 1
      .parent('tr')                                            // row 4
      .find('td:nth-child(3)')                                 // row 4 col 3
      .should('contain', 'value 2')                           
      .parent('tr')                                            // row 4
      .prev('tr')                                              // row 3
      .find('td:nth-child(1)')                                 // row 3 col 1
      .should('contain', 'category 2')
    

    enter image description here