Cos
Cos

Reputation: 51

Q: Cypress fixtures - cannot read property of undefined

I'm trying to use fixtures to hold data for different tests. This is an example of the code. When it gets to the second test I'm getting 'Cannot read property 'email' of undefined'.

Any ideas why and how I can get around that? I'm new to this and followed a course where they said the whole point of using fixtures in the 'before' was to have the data accessible to everything. Is that wrong?

Thank you

describe('Example', function() {
  before(function() {
    cy.fixture('dataFile').then(function(dataJson) {
      this.dataJson = dataJson;
    });
  });

  it('name', function() {
    cy.log(this.dataJson.email);
  });
  it('name2', function() {
    cy.log(this.dataJson.email);
  });
});

Upvotes: 5

Views: 9033

Answers (2)

Alapan Das
Alapan Das

Reputation: 18601

Instead of before() you have to use beforeEach() so that the fixture data is available to all your it() blocks:

describe('Example', function() {
  beforeEach(function() {
    cy.fixture('dataFile').then(function(dataJson) {
      this.dataJson = dataJson;
    });
  });

  it('name', function() {
    cy.log(this.dataJson.email);
  });

  it('name2', function() {
    cy.log(this.dataJson.email);
  });
});

Upvotes: 2

Tahera Firdose
Tahera Firdose

Reputation: 181

You can use the below solution to make it work:

describe('Example', function() {
  let testData;

  before(function() {
    cy.fixture('dataFile').then(function(dataJson) {
      testData = dataJson;
      return testData;
    });
  });

  it('name', function() {
    cy.log(testData.email);
  });
  it('name2', function() {
    cy.log(testData.email);
  });
});

Upvotes: 7

Related Questions