'How to check if an element exists and only then run a test with Cypress?
I want to execute some function only when certain element is present using its data-test id.
Below is what I am trying to do:
cy.getByTestId('checkbox-id').then((el) => {
if (el) {
cy.tableSelectAll();
}
}
Here I am expecting it to execute tableSelectAll() only if there is an element. But this fails saying it couldn't find an element with id "checkbox-id".
How can I fix this? Could someone please help me with this?
Solution 1:[1]
You can use the jquery method .attr to check the presence of the attribute data-testid.
cy.get('checkbox-id').then(($ele) => {
if ($ele.attr('data-testid')) {
cy.tableSelectAll()
} else {
//Do something else
}
})
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 |
