I have an Angular app that I am creating Cypress E2Es for.
A page of the app has a table in which the third column contains a link that goes by the class name 'link ng-star-inserted' that I want the test to click on after finding a specific row.
And I've actually gotten the test to do this - the link is in fact clicked.
But it's not very elegant and it flags the .click() method as an error (even though it does work).
I'm looking for a way to get it to not flag the .click() method as an error.
This is my code...
cy.get(SELECTOR.dataTableBody).should('be.visible')
.contains('tr', 'Text I am looking for in the row I want')
.then($row => {
cy.log('found it');
cy.log('on row ' + $row.index());
//Yes this is kind of ugly. I tried it every other way I could think of and this is the only way it worked
let cellWithLink = $row.find('td:nth-child(3)');
cellWithLink.children().get(0).getElementsByClassName('link ng-star-inserted').item(0).click();
});
And this is a shot of where the IDE flags click() as an error - even though it does actually work.
Thanks much!
From the test code, the HTML looks something like
<table>
<tbody class="p-datatable-tbody">
<tr>
<td></td>
<td>Some text</td>
</tr>
<tr>
<td>Text I am looking for in the row I want</td>
<td></td>
<td>
<span>
<a class="link ng-star-inserted">Click me</a></td>
</span>
</tr>
</tbody>
</table>
Checking the type
returned from .getElementsByClassName()
, you can see it's an HTMLCollection which is a generic collection of elements.
cy.get('table').should('be.visible')
.contains('tr', 'Text I am looking for in the row I want')
.then($row => {
let cellWithLink = $row.find('td:nth-child(3)')
const link = cellWithLink.children()
.get(0)
.getElementsByClassName('link ng-star-inserted')
// .item(0)
// .click()
console.log(link) // result of getElementsByClassName()
})
The item(0)
method returns an Element which doesn't have a .click()
method (since this type is for all elements, not just clickable ones)
Presuming it's the typescript checker that throws the red squiggly (and since you are running Angular), you could try type-casting to HTMLElement which does have a click()
method.
cy.get('table').should('be.visible')
.contains('tr', 'Text I am looking for in the row I want')
.then($row => {
let cellWithLink = $row.find('td:nth-child(3)')
const link = cellWithLink.children()
.get(0)
.getElementsByClassName('link ng-star-inserted')
.item(0);
// .click()
(link as HTMLElement).click()
})
Your test is starting with Cypress queries, then shifting to jQuery queries and then using native HTML queries (starting at .get(0)
).
If you want to keep it Cypress all the way, this should be enough:
cy.get('table').should('be.visible')
.contains('tr', 'Text I am looking for in the row I want')
.find('td:nth-child(3)')
.find('.link.ng-star-inserted')
.click()