好的,所以我有以下代码:
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
});
我想测试每个项目,如果条件错误,我想在变量“ Fails”中加1。
然后,最后,如果Fails为0,则没有错误,我希望它记录消息“ NO FAILS”。问题是,即使变量在EACH内部变为1,在外部也变为0。
这让我很沮丧,因为Im曾经用C#和C#编写代码,因为变量的声明不在每个代码的范围之内,所以可以工作。
你们有什么建议?
答案 0 :(得分:2)
JavaScript异步运行,这意味着您的代码没有按顺序运行。因此,在您的情况下,首先执行Outside the each:
,然后执行Inside the each:
之后。为了确保每个外部在每个内部之后运行,您必须使用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)
})
})