'Cypress: Access the td next to a known one within a table
Can anybody help?
I need to write a cypress locator with a table name and the real name, but click on the checkbox in a td next to the real name label. so far I have:
cy.contains('[tabletitle]', 'XYZ').should('be.lengthOf', 1)
.closest('table')
.contains('td', 'REALNAME').should('be.lengthOf', 1)
.parentsUntil('tr[name='tr-xyz']')
.get('input[type="checkbox"]').check();
I tried closest instead of parentsUntil, but it always jumps above the table name and then ergo click on all the input checkboxes of all the tables on the page. I want it to stay within a tr and just clicks on the checkbox in the above td (within the table). Here is a scetch of the page:
<table name='xyz'><div tabletitle>XYZ</div>
<tr name='tr-efg'>
<td><div><div name='td-xyz'><input type="checkbox"></div></div></td>
<td><div someOtherDiffsandTD></div>
<td><div name='realName1'>REALNAME</div></td>
<td ...etc
<tr name='tr-efg'>
...same as first line with different realname
<tr name='tr-efg'>
... etc ...
</table>
<table name='abc'>
<tr name='tr-efg'>
...same as first table with first td containing a checkbox and second td a cell with the realname...
Solution 1:[1]
To navigate to the table element after selecting the tile, just use .parent() - assuming the table is the direct parent of the title element.
cy.contains('div[tabletitle]', 'XYZ') // tabletitle div with "XYZ"
.parent() // table
.should('be.lengthOf', 1)
.within(() => { // limit to this table
cy.contains('tr', 'REALNAME') // row with "REALNAME" in one of the columns
.should('be.lengthOf', 1)
.find('input[type="checkbox"]') // find, not get
// otherwise all inputs on page are returned
.check() // ?
})
I suspect the HTML you show isn't the full picture, there should be a <tbody> around the <tr> and the title is oddly placed, I would expect it to precede the <table>.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
