好的,所以,我有这个代码:
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
});
我想测试每个项目,如果条件错误,我想向变量“失败”添加 1。
然后,最后,如果 Fails 为 0,则没有错误,我希望它记录消息“NO FAILS”。问题是,即使变量在 EACH 内部变为 1,当在 EACH 外部时,它又变回 0。
这对我来说太令人沮丧了,因为我过去常常编写 C# 代码,而在 C# 中,这会起作用,因为变量的声明位于each 之外。
你们有什么建议?
最佳答案
JavaScript 异步运行,这意味着您的代码不会按顺序运行。因此,在您的情况下发生的情况是首先执行 Outside the every:
,然后执行 Inside the every:
。为了确保Outside every在inside every之后运行,您必须使用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)
})
})
关于variables - 柏树 |无法更改每个循环内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64109273/