This is the code I’m using:
it('Test to stop a FOR loop', function () {
cy.visit('https://docs.cypress.io/guides/overview/why-cypress');
for (let i = 0; i < 5; i++) {
cy.wait(1000);
cy.url().then((url) => {
cy.log(`**${url}**`);
if (url.includes('api')) {
break; // This fails
}
if (url.includes('overview')) {
cy.log('**The URL includes OVERVIEW**');
cy.get('[href="/api/table-of-contents"]').click();
};
if (url.includes('plugins')) {
cy.log('**The URL includes PLUGINS**');
cy.get('.navbar__inner > :nth-child(1) > :nth-child(3)').click();
};
});
};
});
I want to iterate through several pages and stop when the script meets an specific URL. I have tried using return
instead of break
but that doesn’t work. Any thoughts on how to do that?
I have tried:
if (url.includes('api')) {
return;
};
But looks like that doesn’t stop the flow
2
Answers
I think the
return
statement in cypress won’t exit the loop or function as it behaves differently than in synchronous JavaScript.I add code below.
In this code, the
iterate
function is called recursively for each iteration.This ensures that each iteration waits for the asynchronous Cypress commands to finish before moving on to the next iteration.
The recursion will stop when the desired condition
(url.includes('api'))
is met.But what exactly do you want to test? You’ve called cy.visit() only once and provided a single URL, so you can’t iterate through several pages in this manner. The goal of Cypress is to create assertions that compare two things together and evaluate whether they have failed or passed.