I’m new to Cypress and JavaScript. I want to create a loop that executes a request with different values until I get a certain response.
let continue_loop = 1;
loginLoop: for (let i = 1; i < 100; i++) {
cy.request({
// url: Cypress.env("web_api")+"/1.0/user/login",
url: Cypress.env("api").staging + "/1.0/user/login",
method: "POST",
failOnStatusCode: false,
body: {
email: "email" + i + "@email.com",
password: "Helloworld10",
},
}).then((response) => {
if (response.status == 403) {
continue_loop = 2;
}
});
if (continue_loop == 2) {
break loginLoop;
}
}
It seems that continue_loop
only gets the value 2
within the then block, because after it always returns to 1 so the loop never breaks. I also tried to use Cypress aliases but it’s the same result. How can I achieve this?
2
Answers
Cypress, annoyingly, does not use promises but "something that has a .then function" instead. Of course, we can just turn those into real promises by wrapping them and then awaiting those:
Cypress aliases are provided to bridge the gap between synchronous code like for-loops and asynchronous commands like
cy.request()
.You would need to
break
condition inside the loop,continue_loop
istrue
This reproducible example shows how to do equivalent logic to
async/await
in a Cypress test.With a Promise wrapper
Using a Promise wrapper works for this simple command, but could fail for more complex command chains.
Cypress issues a warning in the console.
The warning thrown in the console