3

我正在尝试通过赛普拉斯中的夹具从 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但没有成功。

4

2 回答 2

3

不是黄瓜用户,但在普通赛普拉斯测试中,您只能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().

于 2021-05-13T09:36:07.580 回答
2

赛普拉斯文档中所述

如果您使用此测试上下文对象存储和访问夹具数据,请确保使用 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
        })
    })
于 2021-05-13T09:38:35.887 回答