以前来自json-fixture的Cypress加载数据

我正在尝试通过Cypress中的Fixture从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,但没有成功。


解决方案

不是黄瓜用户,但在素柏测试中,您只能通过将回调设置为函数而不是箭头函数来访问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');
}

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

相关文章