Reputation: 135
I have a table I'm testing that the column headers are correct. The problem is .contains()
only ever returns one element.
I can repeat the code for each instance, but it seems quite verbose. Feel I must be missing something in Cypress commands that can do this better.
cy.get('th').eq(0).contains('Batman')
cy.get('th').eq(1).contains('Robin')
cy.get('th').eq(1).contains('The Flash')
/// etc
<table>
<caption>Superheros and sidekicks</caption>
<colgroup>
<col>
<col span="2" class="batman">
<col span="2" class="flash">
</colgroup>
<tr>
<td> </td>
<th scope="col">Batman</th>
<th scope="col">Robin</th>
<th scope="col">The Flash</th>
<th scope="col">Kid Flash</th>
</tr>
<tr>
<th scope="row">Skill</th>
<td>Smarts</td>
<td>Dex, acrobat</td>
<td>Super speed</td>
<td>Super speed</td>
</tr>
</table>
Upvotes: 3
Views: 3946
Reputation: 10555
You can tidy up the test by mapping elements to inner texts.
Note, specify the first row with tr:eq(0)
const expectedHeaders = ['Batman', 'Robin', 'The Flash', 'Kid Flash']
cy.get('tr:eq(0) th')
.then($th => [...$th].map(th => th.innerText)) // map to texts
.should('deep.eq', expectedHeaders)
Upvotes: 3
Reputation: 7135
If you store the expected in an array, you could use .each()
to iterate through each th
.
const expected = ['Batman', 'Robin', 'Flash', 'Kid Flash']
cy.get('tr').eq(0)
.children('th')
.each(($th, index) => {
cy.wrap($th).should('have.text', expected[index]);
});
Upvotes: 2
Reputation: 31954
One option would be to select the row above, then use .children()
to get a list of all the headers.
You can then chain multiple assertions about that list
cy.get('tr').eq(0) // row containing the heasers
.children('th') // collection of header elements
.should('contain', 'Batman') // assert 1st text
.and('contain', 'Robin') // assert 2nd text
.and('contain', 'The Flash') // assert 3rd text
Upvotes: 3