Use case: I have to search and click the course. I have 10 pages, each page contains 20 courses. I need to find the course(which is random). If the course is available in the first page, it will click and exit from the loop. If the course is not found in the first page, it should click on next button until course. If next button is reached to last page it will verify the next button is disabled, then it should log the "reached last page. but course not found". I have tried with below code using ".each" but it's continuously clicking next page even course is found in 3rd page.
I would appreciate it if anyone shared the solution for this.
When ("I buy the course {string},(course:string)=>{
cy.get("div[slot='title']").each(($el) => {
cy.wrap($el).find("span:nth-of-type(1)").invoke("text").then((text) => {
cy.log(text);
if (text.includes(course)) {
cy.wrap($el).parents(learningPathCards).find(pathCardTitles).shadow().find("cu-buttons[value*='$']").shadow().find(".btn.btn-sm.primary span").click();
return false;
} else {
// if (cy.get(nextButton).shadow().find("cu-navigation-buttons[type='next']").shadow().find("button[title='Next Page']").contains("disabled")) {
// cy.log("No more pages");
// break;
// }
cy.get(nextButton).shadow().find("cu-navigation-buttons[type='next']").shadow().find("button[title='Next Page']").then(($button) => {
if (!$button.is('disabled')) {
cy.wrap($button).click()
}
cy.wait(1000)
})
}
})
}) })
You are trying to "early exit" the
.each()
loop by usingreturn false
, as shown here Return early...but it isn't working in your case.
The reason is that your
return false
statement is wrapped inside thecy.wrap($el).find(..).invoke(..).then((text)
chain, and it becomes unable to perform the "return early" feature of the.each()
command.Luckily, the
.each()
can be moved further down the chain to make this possible:The
each()
will now exit early because thereturn false
is synchronously called.NOTE you may have trouble with
click()
if it triggers change to the page elements.