How to access alias in different test?

Viewed 82

I have an alias defined in 1 test and I would like to use the result in a different test:

it('fills in the login form', () => {
    cy.intercept({
        method: 'POST',
        url: `${Cypress.env('apiURL')}/api/v1/user/login`,
    }).as('login');
    cy.get('[data-cy="inputEmailAddress"]').type(company.users[0].email);
    cy.get('[data-cy="inputPassword"]').type(company.users[0].password);
    cy.get('[data-cy="buttonLogin"]').click();
});

it('does stuff', () => {
    cy.get('@login')
        .its('response')
        .then((res) => {
            expect(res.statusCode).to.eq(200);
        });
});

But I'm getting an error:

cy.get() could not find a registered alias for: @login. You have not aliased anything yet.

Any suggestions on how to make the alias available in a different test?

2 Answers

From the Cypress Docs

Mocha automatically shares contexts for us across all applicable hooks for each test. Additionally, these aliases and properties are automatically cleaned up after each test.

So basically at the end of each test cypress clears all the aliases. So for the above code to work, you have move the intercept method to beforeEach(). Something like:

describe('Test Suite', () => {
  beforeEach(() => {
    cy.intercept({
      method: 'POST',
      url: `${Cypress.env('apiURL')}/api/v1/user/login`,
    }).as('login')
  })

  it('fills in the login form', () => {
    cy.get('[data-cy="inputEmailAddress"]').type(company.users[0].email)
    cy.get('[data-cy="inputPassword"]').type(company.users[0].password)
    cy.get('[data-cy="buttonLogin"]').click()
  })

  it('does stuff', () => {
    cy.get('@login')
      .its('response')
      .then((res) => {
        expect(res.statusCode).to.eq(200)
      })
  })
})

You can't use an alias across tests, Cypress clears them to keep state clean.

However it's just javascript - closure variables can be used.

let login;

it('fills in the login form', () => {
    cy.intercept(...)
      .then(interception => login = interception);
    ... 
});

it('does stuff', () => {

    cy.wrap(login)
      .its('response')
      .then((res) => {
          expect(res.statusCode).to.eq(200);
      });
});

Shared context

Also, the .as('login') command set's a variable on the Mocha context (same name as alias) which is not cleared between tests.

it('fills in the login form', () => {
    cy.intercept(...)
      .as('login');
    ... 
});

it('does stuff', function() {    // function syntax to access "this" scope

    cy.wrap(this.login)          // access persistent scoped variable
      .its('response')
      .then((res) => {
          expect(res.statusCode).to.eq(200);
      });
});
Related