The table:
<tr id="row">
<td></td>
<td></td>
<td>Text</td>
<tr id="row">
<td></td>
<td></td>
<td>Not text</td>
Each row has the same ID. None of the td elements have any identifier.
Mission:
Loop through the the table and check each td element number 3 of each row for a text match.
I'm finding this a bit difficult, coming from Java/Kotlin and Selenium, since it doesn't seem possible in Cypress to create an array containing web elements, and then check the length of that array (number of elements).
So, how to loop through each row and get the third <td>
element in each row?
I've tried this:
cy.get("[data-e2e-selector=row]").each(() => {
cy.pause()
cy.get("[data-e2e-selector=sak-rad]").get("td").eq(2).should('contain', "Text")
})
This obviously loops trough each tr element with id="row", but the line (after the pause) which checks the third td seems to check the same td element every iteration. For me, it looks like I'm checking the same row every time, since there's no iterator in the line. But how to make the code check row 0, row 1, 2 etc. for each iteration?
cy.each()
can yield the element currently in the iteration (as well as the current index, and the original collection yielded).
From this, you apply your logic under each row
element yielded.
cy.get("[data-e2e-selector=row]")
.each(($el) => {
cy.wrap($el) // add the element back into a Cypress command chain
.find('td') // search the yielded element for `td` elements
.eq(2) // yield the third td element
.should('have.text', 'Foo');
});
If the text will vary based on the row, you could define your expected values in an array, and use the yielded index from cy.each()
to call the expected from that array.
const expectedValues = ['foo', 'bar', 'baz'];
cy.get("[data-e2e-selector=row]")
.each(($el, index) => {
cy.wrap($el) // add the element back into a Cypress command chain
.find('td') // search the yielded element for `td` elements
.eq(2) // yield the third td element
.should('have.text', expectedValues[index]);
Additionally, if the element being the third element was not important, you could bypass the .find().eq()
and use cy.contains()
to yield an element with the text value expected.
cy.get("[data-e2e-selector=row]")
.each(($el) => {
cy.wrap($el)
.contains('foo')
.should('exist'); // redundant but explicit check that the element is found
});