首页 > 解决方案 > 赛普拉斯中的异步性和变量覆盖

问题描述

我的问题是,您如何覆盖超出此范围的异步函数中的变量?我在这里读到问题是缺少回调。添加回调后,更改它的范围之外的变量(但变量本身仍然在正确的范围内)返回“未定义”。我究竟做错了什么?

测试:

const savedVariableCallback = (variable) =>
  console.log(`Variable saved ${variable}`);

describe(() => {
      ...
      it("Sample input type", () => {
         let fixValue;
         cy.fixture("example.json").then(({ email }) => {
            actionsPage
            .selectSampleInput()
            .then((input) => {
               checkAmountOfElements(input, 1);
               checkVisiblity(input);
            })
            .type(email)
            .then((input) => {
               checkIfValue(input, email);
               fixValue = "Nice work";
               savedVariableCallback(fixValue);
            });
         });
         cy.log(`fixValue is: ${fixValue}`);
     });
})

我希望第一个日志显示Variable saved Nice work,第二个日志显示fixValue is: Nice work变量。但是现在,我进入第一个日志Variable saved Nice work,但在第二个我得到undefined. 我希望该变量可以在it()方法范围内访问。

标签: javascriptasynchronouscallbackcypress

解决方案


编辑:由于参考不起作用,我建议使用别名来接近它

const savedVariableCallback = (variable) =>
    console.log(`Variable saved ${variable}`);

describe(() => {
...
    it("Sample input type", () => {
        cy.fixture("example.json").then(({ email }) => {
            actionsPage
                .selectSampleInput()
                .then((input) => {
                    checkAmountOfElements(input, 1);
                    checkVisiblity(input);
                })
                .type(email)
                .then((input) => {
                    checkIfValue(input, email);

                    let fixValue = "Nice work";
                    savedVariableCallback(fixValue);
                    cy.wrap(fixValue).as('fixValue')
                });
        });
        cy.get('@fixValue')
            .then(fixValue => {
                cy.log(`fixValue is: ${fixValue.value}`);
            })
    });
})

推荐阅读