Reputation: 95
I am storing user mocked user creds in a fixture file, and i want to access that data in a before statement, so that each test in that file can have access to a username and password variable. I Know that I can pull in the fixture file and then pull out the creds each time, like this:
describe('Login', () => {
before(() => {
cy.fixture('users').as('users')
})
beforeEach(() => {
cy.visit(LOGIN_PAGE)
})
it.only('can enter an email address', function () {
cy.get(EMAIL_INPUT)
.type(this.users.superUser.username)
cy.get(EMAIL_INPUT).should('have.value', this.users.superUser.username)
})
but instead of having to pull out the this.users.superUser.username
each time and assigning it to a variable, I want to be able to do something like const { username } = this.users.superUser
in the before statement and then have access to that variable. How do I store a variable from a fixture file that i can then access in all my tests in the page without having to pull out the var in each test?
Upvotes: 3
Views: 5153
Reputation: 18
If you want to access this fixure in all contexts and it blocks of your spec file, you can do the following:
const USERS;
before (() => {
cy.fixture('users.json').then(($users) => USERS = $users);
}
Then you access the const.
cy.get(EMAIL_INPUT).should('have.value', USERS.superUser.username)
This way the code is cleaner. In case you have more than one user in your json file, then you should only add which one you want to access, like this:
cy.get(EMAIL_INPUT).should('have.value', USERS[1].superUser.username)
Upvotes: 0
Reputation: 445
So once you aliased users it is accessible by any test, no need to assign it to a const. just use it in any test like this : cy.get('@users');
and if you need access to the returned object from your fixture in any test, then you can use .then like traditional promises, so like : cy.get('@users').then((users) => { // now you have access to user object console.log(users.superUser.username);});
Upvotes: 3