I wrote this script On Cypress but if ‘.detailArticle’ is found in ‘#fndRow1’ the for loop continous execution.
I want to break for loop when ‘.detailArticle’ is found
for (let i = 0; i < 5; i++) {
if (i > 0) {
cy.get('#fndRow-' + (i - 1))
.find('input[type="checkbox"]')
.click();
}
cy.get('#fndRow-' + i)
.find('input[type="checkbox"]')
.click();
cy.get('.infosArticleBtn')
.click()
.then(() => {
cy.get('.infosArticleBtn').then(() => {
cy.get('body').then(($body) => {
if ($body.find('.detailArticle).length > 0) {
cy.get('.detailArticle').click();
}
cy.log("article not found");
});
});
});
}
I want to break for loop when ‘.detailArticle’ is found
3
Answers
To break the for loop when .detailArticle is found, you can add a condition to check if it exists inside the then callback function, and use the return false; statement to break out of the loop.
If that works for you.!
Comparing to the previous answer, I propose to use break statement as return false exit the current function. If you use break statement, it will exit only the loop.Good luck!
You can’t call Cypress commands inside a loop and also break early.
The commands happen on the queue asynchronously from the for loop, so you already have 5 iterations set up before the queue starts to run.
What you have is actually an anti-pattern for testing, instead you should know the page data and select elements appropriately without having to loop and "discover" values during the test.