Cypress load data from json - fixture before

Viewed 3514

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.

2 Answers

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
        })
    })
Related