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 using return false
, as shown here Return early
Stop each prematurely
You can stop the
.each()
loop early by returningfalse
in the callback function.
...but it isn't working in your case.
The reason is that your return false
statement is wrapped inside the cy.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:
cy.get('div[slot="title"]').find('span:nth-of-type(1)')
.each($span => {
const text = $span.text()
if (text.includes(course)) {
cy.wrap($span)
.parents(..).find(..).shadow().find(..).shadow().find(..).click()
return false;
} else {
...
}
})
The each()
will now exit early because the return false
is synchronously called.
NOTE you may have trouble with click()
if it triggers change to the page elements.