'How to handle the error if the element doesn't exist in the DOM using Cypress
i want to get the text dynamically using for loop but at certain point the element may not exist, and cypress is trying to find the element and is throwing error.
as is selenium we could have used list to find the element and could handle it, but here cypress is trying to find the dynamic element at some index and if it not present it is throwing error.
for(var i=1; i<40; i++){
try{
cy.get('tbody > :nth-child('+i+') > :nth-child(2)')
.then(($elem) =>{
var sum= $elem.text()
cy.log('---',sum)
})
}catch(err) {
cy.log('error')
break
}
i tried using try catch block as well but it is still not going in catch block
any help would be much appreciated
Solution 1:[1]
Assuming children of tbody are rows tr and cells td, otherwise you may adapt my code below. I would use an each() loop to perform this:
cy.get('tbody > tr').each(($tr, index) => {
if ($tr.find('td').length >= 3) {
let sum = $tr.find('td').eq(2).text();
cy.log('row ' + index + ': ' + sum);
} else {
cy.log('row ' + index + ': Not found')
}
});
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 | PeaceAndQuiet |
