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

Cypress › State, sessions, isolation

Custom commands and cy.session

A custom command gathers a repeated action such as login in one place, so a changed endpoint needs one edit. Cypress.Commands.add registers it in the support file, and in TypeScript it is declared in Chainable. Inside, cy.session is called, with a key built from the role and environment so caches do not mix. The command is kept short and free of assertions, with more complex logic moved into module functions.

Cypress · Sessions and isolation

The login is copied into thirty tests and the password changed. How do you move it into one command?

In a suite login, data creation and form steps repeat in many tests. When the endpoint or the way of authorisation changes, you have to edit everywhere. A custom command gathers a repeated action in one place, and together with cy.session it gives one fast sign-in for all tests. The lesson covers how to write it, type it and where to be careful.

How it works and why. Cypress.Commands.add(name, fn) registers a command in the support file (usually cypress/support/commands.ts, imported by e2e.ts). After that cy.name() is available in every spec. Inside the command you can call any Cypress command, including cy.session. The session key then consists of what tells users apart: the role and, if needed, the environment. For TypeScript the command is declared in the Chainable interface, otherwise the compiler will not know about cy.login.

The layers of sign-in

Test: cy.login("admin")one readable commandCommand: cy.session(id, …)cache by id: role, environmentsetup: cy.request to the APIruns only when there is no cache
Figure 1. The test sees one command and the login details are hidden two layers below.

Example: a typed login command.

// cypress/support/commands.ts
declare global {
  namespace Cypress {
    interface Chainable {
      login(role?: 'user' | 'admin'): Chainable<void>;
    }
  }
}

Cypress.Commands.add('login', (role = 'user') => {
  cy.session(
    [role, Cypress.config('baseUrl')], // id: role and environment
    () => {
      cy.env([role + '_email', role + '_password']).then((env) => {
        cy.request('POST', '/api/auth/login', {
          email: env[role + '_email'],
          password: env[role + '_password'],
        });
      });
    },
    {
      validate: () => {
        cy.request('/api/me').its('status').should('eq', 200);
      },
    },
  );
});

The test now writes cy.login('admin') and does not know how sign-in works. The session key is an array of the role and baseUrl, so the cache for admin on one environment does not clash with another. When the endpoint changes, the fix is in one place.

Limits and alternatives. A custom command should be short and predictable. If it hides assertions or long scenarios, the test reads worse and a failure points at the command, not at a step. For repeated steps with logic a plain function in a module (the App Actions approach) is often handier because it is typed better and supported by the IDE. The special Cypress.Commands.addQuery is needed only for commands that must retry like queries. Inside cy.origin custom commands are unavailable until they are attached inside the block.

And in Playwright:

The role of a custom command is played there by fixtures: a fixture can hand out an already logged-in user, and storageState keeps the session between tests. Typing comes from TypeScript itself with no global interface extension.

Common mistakes.

  • A session key without a role or environment: different users share a cache and a test gets the wrong session.
  • Not declaring the command in Chainable: JavaScript works but TypeScript flags cy.login as unknown.
  • Putting cy.visit and assertions into the command: every test gets hidden behaviour.
  • Not adding validate: an expired session shows up as a random failure in a test.

Check yourself

The command cy.login(role) calls cy.session('user', …) with a fixed id, and a test calls it with the role admin. What goes wrong?

Answer

All roles share one cache under the id 'user', so admin gets the session of an ordinary user (or the other way round). The id must contain the role: cy.session(role, …).

Why extend Chainable if the JavaScript code works anyway?

Answer

It is needed only by the TypeScript compiler: without the declaration cy.login counts as unknown. The declaration also gives autocompletion and argument type checking.

In an interview. Junior: I add custom commands through Cypress.Commands.add in the support file: they gather repeated actions such as login or data creation in one place. In TypeScript they are declared in Chainable. Middle/Senior: I do the login through the API and wrap it in cy.session, composing the key from the role and the environment so caches do not mix. I keep the command short with no assertions and move more complex logic into functions in modules when better types are needed.

More articles in this chapter