Search code examples
cypressalias

Accessing aliases in Cypress with "this"


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
});

Solution

  • The alias is undefined in every test except the first because aliases are cleared down after each test.

    Aliased variables are accessed via cy.get('@user') syntax. 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.


    There does not seem to be a way to explicitly preserve an alias, as the is with cookies

    Cypress.Cookies.preserveOnce(names...)
    

    but this recipe for preserving fixtures shows a way to preserve global variables by reinstating them in a beforeEach()

    let city
    let country
    
    before(() => {
      // load fixtures just once, need to store in
      // closure variables because Mocha context is cleared
      // before each test
      cy.fixture('city').then((c) => {
        city = c
      })
    
      cy.fixture('country').then((c) => {
        country = c
      })
    })
    
    beforeEach(() => {
      // we can put data back into the empty Mocha context before each test
      // by the time this callback executes, "before" hook has finished
      cy.wrap(city).as('city')
      cy.wrap(country).as('country')
    })
    

    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); 
      cy.wrap(user).as('user');              // set as alias
    });
    
    it('first', () => {
      cy.get('@user').then(val => {
        console.log('first', val)            // user alias is valid
      })
    })
    
    it('second', () => {
      cy.get('@user').then(val => {
        console.log('second', val)           // user alias is valid
      })
    })