QA Interview Hub · Knowledge base · Quizzes · Українська

Cypress › State, sessions, isolation

What is cy.session and how do you avoid logging in in every test?

cy.session runs the login once, saves cookies, localStorage and sessionStorage, and restores them in later tests. The data is stored under the id key and setup is not called again. The validate option checks that the restored session is still alive, otherwise setup runs again. One id should match one user or role. After cy.session the page is blank, so the test calls cy.visit itself.

Cypress · Sessions and isolation

There are fifty tests and each logs in. The suite is slow. How do you log in once without breaking isolation?

Test isolation requires every test to have a logged-in user, but a full login fifty times costs time and hurts stability. cy.session logs in once, saves the result and restores it in every following test. The lesson explains how it works, when a session counts as alive and what goes into it.

How it works and why. cy.session(id, setup, options) stores, under the key id, the cookies, localStorage and sessionStorage left after setup. In later tests with the same id Cypress clears the page, restores the saved data and does not call setup. The validate option checks that the restored session is still valid: if a command in it fails or the returned chain or Promise yields false (a plain return false does not count), Cypress runs setup again, and if validate still fails after that, the test fails. cacheAcrossSpecs: true shares the cache between spec files. After cy.session the page is blank: the test itself must navigate to the needed address.

The life of a session

1st call: setuplogin, saving cookies and storagesLater calls: restoreno login; then validatevalidate failed: setup againthe session expired, log in anew
Figure 1. The login happens once, then the session is only restored and checked.

Example: a login command with a session.

Cypress.Commands.add('login', (role = 'user') => {
  cy.session(
    role, // id: a separate cache per role
    () => {
      cy.env([role + '_email', role + '_password']).then((env) => {
        cy.request('POST', '/api/auth/login', {
          email: env[role + '_email'],
          password: env[role + '_password'],
        });
      });
      // the cookie from the cy.request response lands in the browser
    },
    {
      validate() {
        cy.request('/api/me').its('status').should('eq', 200);
      },
      cacheAcrossSpecs: true,
    },
  );
});

beforeEach(() => {
  cy.login('admin');
  cy.visit('/dashboard');
});

The login goes through cy.request, with no form, and Cypress puts the Set-Cookie from the response into the browser. Credentials come from cy.env, not from the test code. If the app keeps a token in localStorage, write it in setup with window.localStorage.setItem and the session will save it just the same.

Limits and alternatives. cy.session stores only cookies, localStorage and sessionStorage. It knows nothing about the server side: if the server revoked a token or the session expired, only validate helps, so without it tests fail in random places. One id must stand for one user: if two roles share a key, the wrong session is restored. If login goes through an external provider, setup may contain cy.origin.

And in Playwright:

The analogue is storageState: a setup project logs in and saves cookies and localStorage to JSON, other projects load the file with the storageState option, and dependencies makes setup run before them. One file per role, and a single test can hold two contexts with different roles at once.

Common mistakes.

  • Skipping validate: the token expired and the test fails not at the login but somewhere later.
  • Forgetting cy.visit after cy.session: the page is blank and cy.get finds nothing.
  • One id for different users: a test for the “admin” role gets the “user” session.
  • Assuming cy.session saves data on the server: it is only a snapshot of browser state.

Check yourself

What happens when, during a session restore, validate gets a 401?

Answer

Cypress treats the session as invalid and runs setup again, that is, logs in anew. If validate fails again after that, the test fails with an error: the login itself is broken.

A test calls cy.login('user') in beforeEach and then cy.get('[data-cy=balance]') without cy.visit and fails. Why?

Answer

After cy.session the page is cleared to about:blank. The session restored cookies but did not open anything. You need cy.visit('/dashboard').

In an interview. Junior: cy.session does this: it runs the login once, saves cookies and storages and restores them in later tests. validate checks that the session is still alive. Middle/Senior: I do the login inside setup through the API. A separate id per role gives quick user switching, and cacheAcrossSpecs shares the session between files. Without validate an expired session causes flaky failures, so it is mandatory.

More articles in this chapter