I'm trying to share values between my before
and beforeEach
hooks using aliases. It currently works if my value is a string but when the value is an object, the alias is only defined in the first test, every test after that this.user
is undefined in my beforeEach hook. How can I share a value which is an object between tests?
This is my code:
before(function() {
const email = `test+${uuidv4()}@example.com`;
cy
.register(email)
.its("body.data.user")
.as("user");
});
beforeEach(function() {
console.log("this.user", this.user); // This is undefined in every test except the first
});
Aliased variables are accessed via cy.get('@user')
or expect(user)
syntax. I understand this is because some commands are inherently asynchronous, so using a wrapper to access the variable ensures it is resolved before being used.
See documentation Variables and Aliases and get.
If you want to access a global user
value, you might try something like
let user;
before(function() {
const email = `test+${uuidv4()}@example.com`;
cy
.register(email)
.its("body.data.user")
.then(result => user = result);
});
beforeEach(function() {
console.log("global user", user);
});
where the then
resolves like a promise, but you should be wary of delay in resolving - the console.log
may run before the then
.