Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cypress fixtures – Cannot read properties of undefined (reading 'data')

I’m trying to use fixtures to hold data for different tests, specifically user credentials. This is an example of the code. When it gets to the second test I’m getting 'Cannot read properties of undefined (reading 'data')'.

Any ideas why and how I can get around that? Is that wrong?

before(function () {
    cy.fixture('credentials').then(function (data) {
        this.data = data;
    })
})

    it('Login correct', () => {
        cy.visit('/')
        loginPage.signIn(this.data.admin.username,this.data.admin.password)
        cy.wait(5000)
        // assertion
        cy.contains('Dashboard').should('be.visible')
    })

And here is my credentials.json file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "admin": {
    "username": "*****",
    "password": "*****"
  }
}

>Solution :

I prefer using closure variables to assign fixture data.

describe('Some Test', () => {
  let data;
  before(() => {
    cy.fixture('credentials').then((fData) => {
        data = fData;
    });
  });

    it('Login correct', () => {
        cy.visit('/')
        loginPage.signIn(data.admin.username, data.admin.password)
        cy.wait(5000)
        // assertion
        cy.contains('Dashboard').should('be.visible')
    })
});

Gleb Bahmutov also recommends using closure variables.

I strongly recommend using closure variables instead of this properties. The closure variables are clearly visible and do not depend on function vs () => {} syntax.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading