← Back to libraryQuestion 183 of 468
🌲CypressAdvanced

cy.session — Caching Login State

📌 Definition:

cy.session caches and restores browser session state (cookies, localStorage, sessionStorage) across tests, so you log in once and reuse the authenticated session — dramatically speeding up suites.

📖 Detailed Explanation:

Logging in before every test is slow and flaky. cy.session(id, setupFn) runs the setup (e.g. an API or UI login) once, snapshots the resulting session, and on subsequent tests RESTORES the snapshot instead of re-running login. You typically wrap it in a custom command: Cypress.Commands.add('login', () => cy.session('user', () => { /* login */ })). An optional validate callback re-checks the session is still valid. Combined with cy.request-based login, cy.session makes authenticated suites fast and deterministic. It also isolates sessions between different users by using distinct ids.

🔑 Key Points:
  • Caches cookies + local/session storage across tests
  • Runs the login setup ONCE, then restores the snapshot
  • Pair with API login (cy.request) for max speed
  • Use distinct ids per user; validate() re-checks validity
🌍 Real-World Example:

A 200-test authenticated suite drops from ~20 minutes to a few minutes after wrapping login in cy.session('admin', apiLogin), because the login only actually runs once and is restored for every other test.

🎯 Scenario-Based Interview Question:

Your suite logs in via UI in beforeEach and takes 20 minutes. How does cy.session help, and what's the ideal combination?