【问题标题】:Cypress load data from json - fixture before赛普拉斯从 json 加载数据 - 之前的夹具
【发布时间】:2021-05-13 09:24:33
【问题描述】:

我正在尝试通过赛普拉斯中的夹具从 json 文件中检索一些数据,但这些数据根本无法识别。

before(() => {
cy.fixture('example').then(function (data) {
    console.log("this", data.user);
})

})

控制台输出用户,这是有效的。

但在那之后我有一个步骤:

Given("I check data", () => {
    console.log("this", this.data.user);
});

这里的数据是未定义的。

我也尝试在before 内设置:

this.data = data 但没有帮助。我也尝试使用beforeEach,但没有成功。

【问题讨论】:

标签: javascript cypress cypress-cucumber-preprocessor


【解决方案1】:

不是黄瓜用户,但在普通 Cypress 测试中,您只能通过将回调设为函数而不是箭头函数来访问 this

Given("I check data", function() {
  console.log("this", this.data.user);
});

我认为您可能还必须为数据起别名

before(() => {
  cy.fixture('example')
    .then(function (data) {
      console.log("this", data.user)
    })
    .as('data');
}

请注意,赛普拉斯会在两次测试之间清除别名,因此您需要使用 beforeEach() 而不是 before()

【讨论】:

  • 谢谢,这就是问题所在,只是用函数替换箭头函数。我不知道这件事。现在完美运行!
【解决方案2】:

正如cypress docs中提到的那样

如果您使用此测试上下文存储和访问夹具数据 对象,请确保使用 function () { ... } 回调。否则 测试引擎不会让 this 指向测试上下文。

将箭头函数更改为函数应该可以工作:

Given("I check data", function() {
    console.log("this", this.example.user);
});

还有你的beforeEach() 块:

   beforeEach(function () {
        cy.fixture('example').then(function (example) {
            this. example = example
        })
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多