Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Cypress cy.session: Speed Up Tests with Login Caching

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Cypress tests often slow down because every test re-runs the full login flow, hitting your server and waiting for network responses. The cy.session() command fixes this by caching login state and reusing it across tests, cutting seconds off each test run. This guide shows you how to set it up, avoid common pitfalls, and get the most out of it.

What You'll Need

  • A Cypress project (version 9.6.0 or later, as cy.session() was introduced in Cypress 9.6.0).
  • An existing login flow you can automate (e.g., UI login, API login, or programmatic session setup).
  • Basic understanding of Cypress custom commands and beforeEach hooks.

Step-by-Step

  1. Identify your login flow. Determine how your app authenticates. Common methods: typing credentials into a UI form, calling a login API endpoint, or setting a token directly in localStorage. Choose the fastest reliable method—usually API login is quicker than UI.
  2. Create a custom command for login. In your cypress/support/commands.js file, define a command that performs the actual login. For example:
    Cypress.Commands.add('login', (username, password) => {
      cy.request({
        method: 'POST',
        url: '/api/login',
        body: { username, password }
      }).then((resp) => {
        window.localStorage.setItem('token', resp.body.token);
      });
    });
    This command will be called inside the session.
  3. Wrap the login in cy.session(). Modify your login command to use cy.session(). The first argument is a unique identifier for the session (e.g., username), the second is a callback that performs the login, and the third is optional options object.
    Cypress.Commands.add('login', (username, password) => {
      cy.session(username, () => {
        cy.request({
          method: 'POST',
          url: '/api/login',
          body: { username, password }
        }).then((resp) => {
          window.localStorage.setItem('token', resp.body.token);
        });
      });
    });
    Now, when the command runs, Cypress will check if a valid session for that username exists. If yes, it restores the browser state (cookies, localStorage, etc.) instead of re-running the login.
  4. Call the login command in a beforeEach hook. In your test file, use beforeEach to ensure each test starts with a logged-in state:
    beforeEach(() => {
      cy.login('testuser', 'password');
    });
    The first test will perform the actual login; subsequent tests will reuse the cached session.
  5. Configure session behavior (optional). You can pass options to cy.session() to control validation and caching. For example, to validate the session is still valid before reusing, use validate:
    cy.session(username, () => { ... }, {
      validate: () => {
        cy.getCookie('sessionId').should('exist');
      }
    });
    If the validation fails, the session is recreated.
  6. Run your tests and observe the speedup. Run Cypress and watch the command log. On the first test, you'll see the login steps. On subsequent tests, you'll see a cy.session restore step that is much faster.

Common Mistakes

  • Using the same session ID for different users. If you have multiple users, include the username or a unique identifier in the session ID. Otherwise, tests may reuse the wrong user's state.
  • Not clearing sessions between runs. Cypress clears sessions by default in a new run, but if you run tests in the same browser profile without a clean slate, stale sessions can cause issues. Use Cypress.session.clearAllSavedSessions() in a before hook if needed.
  • Ignoring session expiry. If your app's session expires quickly, the cached session may be invalid. Use the validate option to check for a valid token or cookie and re-login if needed.
  • Performing UI login inside the session callback. While possible, UI login is slower and more brittle. Prefer API login or direct state manipulation for speed.

Tips

  • Use a separate session for each user role. For example, cy.session('admin', ...) and cy.session('user', ...) to avoid cross-contamination.
  • Combine with Cypress.Cookies.preserveOnce() if needed. If you have tests that modify cookies, you might need to preserve them across tests, but cy.session() usually handles this automatically.
  • Keep session setup minimal. Only include steps that are necessary to establish the authenticated state. Avoid extra UI interactions that slow down the initial login.
  • Test session validation. Ensure your validate function accurately reflects a valid session. A common check is verifying that a token exists and is not expired.

Troubleshooting

  • Session not being reused. Check that you're using the same session ID. If the ID differs (e.g., due to a random value), the session won't match. Also, ensure the session hasn't expired—Cypress may clear sessions if the browser context is closed.
  • Login state not fully restored. Some apps store auth data in IndexedDB or other storage that cy.session() may not capture by default. You can specify additional storage to cache using the cacheAcrossSpecs option or manually set the storage in the callback.
  • Tests failing after session reuse. If the app behaves differently on a fresh login vs. a restored session (e.g., onboarding modals), your tests might break. In such cases, either adjust the validation to detect the modal or add a step to dismiss it in the session setup.
  • Session cache causing interference. If you have tests that deliberately log out, you may need to clear the session after those tests. Use Cypress.session.clearCurrentSessionData() or cy.session() with a new ID.

Frequently Asked Questions

Does cy.session work with UI login?

Yes, you can put UI login steps inside the callback. It will still cache the resulting state, but the initial login will be slower than API login.

Can I use cy.session with multiple users in one test file?

Yes, just use different session IDs for each user. For example, cy.session('user1', ...) and cy.session('user2', ...).

Does cy.session work across spec files?

By default, sessions are scoped to a single spec file. To share sessions across specs, set cacheAcrossSpecs: true in the options. Note that this requires Cypress 12.0.0 or later.

How do I clear all saved sessions?

Use Cypress.session.clearAllSavedSessions() in a before hook or in your test setup.

Can I use cy.session for non-login state?

Yes, you can use it to cache any browser state, such as setting up a specific localStorage or cookie configuration. The session ID can be any string.

Does cy.session speed up tests significantly?

It depends on how slow your login flow is. If login takes 5 seconds, and you have 100 tests, you save ~500 seconds. Even with fast logins, the savings add up.