Reputation: 1516
Trying to get a Cypress script to click a hyperlink based on two values - the text of the hyperlink in column 1 and the value of the cell in the second column:
<tbody>
<tr>
<td><a href="/id/343408">Anything</a></td>
<td>Casualty</td>
</tr>
<tr>
<td><a href="/id/338494">Declined Prospect</a></td>
<td>Casualty</td>
</tr>
<tr>
<td><a href="/id/343408">Declined Prospect</a></td>
<td>Package</td>
</tr>
<tr>
<td><a href="/id/338494">Declined Prospect</a></td>
<td>Casualty</td>
</tr>
<tr>
<td><a href="/id/338432">Irrelevant</a></td>
<td>Package</td>
</tr>
</tbody>
cy.get('a').contains('Declined Prospect').click()
fails because there's more than one hyperlink with that value. The id is not useful because it's dynamic.
In the example above, I want to click Declined Prospect when the second column is Casualty (but the order of the rows may vary and values in the first and second column are repeated - but only once for the combination).
Any thoughts?
Upvotes: 2
Views: 1816
Reputation: 23483
The trick is to target <td>Casualty</td>
then click the preceding <td><a>
.
There are quite a few ways to get to sibling elements, the simplest in this case is prev().
cy.contains('td', 'Casualty') // target the 'marker' element
.prev() // move to the previous sibling
.click()
Approach from row and move inwards
To target a row with a specific combination of text in some of it's cells, just concatenate the text and use contains()
.
cy.contains('tr', 'Declined Prospect Casualty') // target unique text within children
This even works when there are other cells with text that's not relevent to the search, e.g
<tr>
<td><a href="/id/338494">Declined Prospect</a></td>
<td>Casualty</td>
<td>Irrelevent text here</td>
</tr>
Then you can walk down the HTML tree,
cy.contains('tr', 'Declined Prospect Casualty') // target unique text within children
.find('td a') // descendant of previous subject
.click()
Upvotes: 3
Reputation: 2486
I think this can be useful: https://github.com/cypress-io/cypress-xpath
You can create selectors in xpath instead of css and in xpath you can search tree by text. e.g:
cy.xpath("//text() = 'Declined Prospect'")
==================================Edited====================
You can merge couples of xpatch selectors: it will looks like this //tr[td='Casualty']/td/a
Upvotes: 1