简体   繁体   中英

Cypress load data from json - fixture before

I am trying to retrieve some data from a json file via fixture in Cypress, but the data is not recognized at all.

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

})

The console outputs the user, this is working.

But after that I have a step:

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

And here the data is undefined.

I tried to set inside before also:

this.data = data but did not help. I also tried to use beforeEach with no success.

Not a cucumber user, but in plain Cypress tests you can only access this by making the callback a function not an arrow function

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

I think you might have to alias the data as well

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

Note that Cypress clears aliases in between tests, so you would need to use beforeEach() instead of before() .

As mentioned here in the cypress docs

If you store and access the fixture data using this test context object, make sure to use function () {... } callbacks. Otherwise the test engine will NOT have this pointing at the test context.

Changing the arrow function to function should work:

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

And your beforeEach() block:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM