Cypress.Cookies.preserveOnce('session_id') isn't working when called in afterEach hook

Viewed 407

I'm working with cypress tests and I want to avoid having to log in before each test. so, I wanted to preserve the cookies in each test file.

The log statement in the afterEach hook is triggered, however cookies are cleared in the second testcase.

describe('Users Page Scenarios', () => {
    before(() => {
        myApp.pages.Login.navigate();
        myApp.pages.Login.login(
            credentials.globalAdmin.email,
            credentials.globalAdmin.password
        );
    });

    beforeEach('navigate to users page before each test', () => {
        myApp.sharedComponents.Header.navigateToUsers();
    });

    afterEach(() => {
        Cypress.Cookies.preserveOnce('session_id');        
        cy.log('test');
    });

    describe('Users List', () => {
        it('Should redirect the user to users page after clicking on users in the navigation header', () => {
            cy.url().should('eq', `${Cypress.config().baseUrl}/user`);
        });
    })

    describe('New User Creation', () => {
        it('Should open new user modal after clicking on invite administrator', () => {
            myApp.pages.Users.UsersList.inviteAdministrator();
            cy.url().should('eq', `${Cypress.config().baseUrl}/user/new`);
        });

        it('Should create a new user successfully', () => {
            myApp.pages.Users.UsersList.inviteAdministrator();
            myApp.pages.Users.UsersInfo.createNewUser(user.generateUser());
        })
    });
1 Answers

The docs indicate that Cypress.Cookies.preserveOnce('session_id') is used in beforeEach().

Looks like after is too late.

describe('Dashboard', () => {
  before(() => {
    // log in only once before any of the tests run.
    // your app will likely set some sort of session cookie.
    // you'll need to know the name of the cookie(s), which you can find
    // in your Resources -> Cookies panel in the Chrome Dev Tools.
    cy.login()
  })

  beforeEach(() => {
    // before each test, we can automatically preserve the
    // 'session_id' and 'remember_token' cookies. this means they
    // will not be cleared before the NEXT test starts.
    //
    // the name of your cookies will likely be different
    // this is an example
    Cypress.Cookies.preserveOnce('session_id', 'remember_token')
  })

If you have localStorage or sessionStorage to preserve, or you have not identified all cookies correctly, try with cy.session()

beforeEach(() => {                 // must be beforeEach()
  cy.session('mySession', () => {  // preserves localStorage, sessionStorage, cookies
    myApp.pages.Login.navigate();
    myApp.pages.Login.login(...);  // only called once (despite beforeEach())
  })
})
Related