【问题标题】:Cypress | Cant change variable inside each loop柏树 |不能在每个循环内更改变量
【发布时间】:2021-01-14 10:55:00
【问题描述】:

好的,所以,我有这个代码:

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,当它在外部时,它又回到 0。

这让我很沮丧,因为我以前写过 C# 代码,而在 C# 中,这会起作用,因为变量的声明在 each 之外。

你们有什么建议?

【问题讨论】:

    标签: variables integer each cypress var


    【解决方案1】:

    JavaScript 异步运行,这意味着您的代码不会按顺序运行。所以在你的情况下发生的是Outside the each:首先执行,然后Inside the each:被执行。要确保 Outside eachinside 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)
       })
    })
    

    【讨论】:

    • 我明白了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2016-06-02
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    相关资源
    最近更新 更多