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:
{
"admin": {
"username": "*****",
"password": "*****"
}
}
Try using closure variables to assign fixture data.
describe('Some Test', () => {
let data; //closure variable
before(() => {
cy.fixture('credentials').then((fData) => {
data = fData;
});
});
it('Login correct', () => {
cy.visit('/')
loginPage.signIn(data.admin.username, data.admin.password) //usage of closure variable to get the values from the fixtures
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.