Reputation: 175
OK, So, I have this code:
Cypress.Commands.add ('MethodName', (argument) => {
var Fails = 0
cy.get('anything').each(Id => {
if (blablabla) {
Fails += 1
cy.log("Inside the each: " + Fails) //prints 1
}
})
cy.log("Outside the each: " + Fails) //prints 0
});
I want to test each item and if a condition is wrong, I want to add 1 to the variable "Fails".
Then, in the end, if Fails is 0, then there are no errors, and I want it to log the message "NO FAILS". The problem is , even if the variable changes to 1 inside the EACH, when its outside, it comes back to 0.
This is so frustrating to me, because Im used to write C# code and in C#, that would work, since the declaration of the variable is outside the each.
What do you guys suggest?
Upvotes: 2
Views: 1118
Reputation: 18626
JavaScript runs asynchronously which means that your codes doesn't run in sequence. So what's happening in your case is Outside the each:
is executing first and after that Inside the each:
is being executed. To make sure that Outside each runs after inside each, you have to use then()
.
Cypress.Commands.add('MethodName', (argument) => {
var Fails = 0
cy.get('anything').each(Id => {
if (blablabla) {
Fails += 1
cy.log("Inside the each: " + Fails)
}
}).then(() => {
cy.log("Outside the each: " + Fails)
})
})
Upvotes: 3