0
0
Cypresstesting~15 mins

cy.session() for session caching in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - cy.session() for session caching
What is it?
cy.session() is a command in Cypress that helps save and restore browser session data like cookies and local storage. It lets tests reuse login or setup steps without repeating them every time. This makes tests faster and more reliable by avoiding repeated actions. It works by caching session information and restoring it automatically when needed.
Why it matters
Without session caching, tests must log in or set up the same state repeatedly, which wastes time and can cause flaky tests if the setup fails. cy.session() solves this by remembering the session once created and reusing it, speeding up test runs and making them more stable. This saves developers time and reduces frustration during testing.
Where it fits
Before learning cy.session(), you should understand basic Cypress commands, how to write tests, and how browser sessions work (cookies, local storage). After mastering cy.session(), you can explore advanced test optimization techniques and parallel test execution.
Mental Model
Core Idea
cy.session() saves a browser session once and restores it later to avoid repeating setup steps in tests.
Think of it like...
It's like taking a snapshot of your desk setup so you can quickly restore it later instead of arranging everything from scratch each time.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Run test first│──────▶│ Save session  │──────▶│ Reuse session │
│ time: login   │       │ (cookies, etc)│       │ in next tests │
└───────────────┘       └───────────────┘       └───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding browser sessions basics
🤔
Concept: Learn what browser sessions are and how cookies and local storage keep user data.
A browser session stores data like cookies and local storage to remember who you are or what you did. For example, when you log in to a website, it saves a cookie so you stay logged in. Tests often need this data to simulate real user actions.
Result
You know that sessions hold important data that tests must handle to simulate logged-in users.
Understanding session data is key because cy.session() works by saving and restoring this data to speed up tests.
2
FoundationBasic Cypress test without session caching
🤔
Concept: Write a simple test that logs in every time without caching the session.
cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() cy.url().should('include', '/dashboard')
Result
The test logs in every time it runs, repeating the same steps.
Repeating login slows tests and can cause failures if login changes or is slow.
3
IntermediateIntroducing cy.session() for caching
🤔Before reading on: do you think cy.session() stores only cookies, or all session data like local storage too? Commit to your answer.
Concept: cy.session() caches all session data including cookies and local storage to reuse later.
cy.session('user-session', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() }) cy.visit('/dashboard') cy.url().should('include', '/dashboard')
Result
The login runs once, then the session is reused in later tests without repeating login steps.
Knowing cy.session() caches full session data helps you trust it to restore the exact user state.
4
IntermediateUsing cy.session() with test isolation
🤔Before reading on: do you think cy.session() shares sessions across all tests automatically, or do you need to name sessions? Commit to your answer.
Concept: You must name sessions uniquely to reuse them across tests and keep tests isolated.
describe('Dashboard tests', () => { beforeEach(() => { cy.session('user-session', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() }) }) it('shows dashboard', () => { cy.visit('/dashboard') cy.contains('Welcome') }) it('shows profile', () => { cy.visit('/profile') cy.contains('User Profile') }) })
Result
Both tests reuse the same cached session, avoiding repeated logins.
Naming sessions lets you control when and how session data is reused, improving test speed and reliability.
5
AdvancedHandling session invalidation and updates
🤔Before reading on: do you think cy.session() automatically updates cached sessions if login details change? Commit to your answer.
Concept: You must manually clear or update sessions when session data changes to avoid stale sessions.
cy.session('user-session', () => { // login steps }, { validate() { // check if session is still valid, e.g. by visiting a page cy.visit('/dashboard') cy.contains('Welcome') } })
Result
The session is validated before reuse; if invalid, login runs again to update the session.
Knowing how to validate sessions prevents flaky tests caused by expired or changed session data.
6
ExpertInternal caching and performance optimization
🤔Before reading on: do you think cy.session() stores session data in memory only, or persists it between test runs? Commit to your answer.
Concept: cy.session() caches session data in memory during a test run but does not persist it between runs to keep tests isolated.
Cypress stores session data in memory and restores it before each test needing it. This avoids repeated logins but resets between runs to prevent cross-test pollution. Developers can combine cy.session() with other caching strategies for even faster CI pipelines.
Result
Tests run faster within a single run, but sessions reset on new runs to keep tests clean.
Understanding cy.session() caching scope helps design tests that balance speed and isolation.
Under the Hood
cy.session() works by running a setup callback once to create session data like cookies and local storage. It then saves this data in memory. Before each test that uses the session, Cypress restores the saved cookies and local storage to the browser, simulating a logged-in or pre-set state. It also supports a validation callback to check if the session is still valid and rerun setup if needed.
Why designed this way?
Cypress designed cy.session() to speed up tests by avoiding repeated setup steps while keeping tests isolated. Storing session data in memory per test run prevents cross-test contamination and flaky tests. Persisting sessions between runs would risk stale data and unreliable tests, so Cypress chose a balance between speed and reliability.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Setup session │──────▶│ Save session  │──────▶│ Restore session│
│ callback runs │       │ data in memory│       │ before tests  │
└───────────────┘       └───────────────┘       └───────────────┘
         ▲                                            │
         │                                            ▼
   ┌───────────────┐                           ┌───────────────┐
   │ Validate      │◀──────────────────────────│ Test runs     │
   │ session valid?│                           │ with session  │
   └───────────────┘                           └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does cy.session() persist session data between separate test runs? Commit to yes or no.
Common Belief:cy.session() saves session data permanently so tests can reuse it across different runs.
Tap to reveal reality
Reality:cy.session() only caches session data in memory during a single test run and resets between runs.
Why it matters:Assuming persistence leads to flaky tests because sessions may be stale or invalid after a fresh run.
Quick: Does cy.session() automatically detect when a session is invalid and refresh it? Commit to yes or no.
Common Belief:cy.session() always knows if the session expired and refreshes it automatically without extra code.
Tap to reveal reality
Reality:You must provide a validation callback to check session validity; otherwise, stale sessions may be reused.
Why it matters:Without validation, tests can fail unpredictably due to expired sessions.
Quick: Does cy.session() share session data between different named sessions? Commit to yes or no.
Common Belief:All sessions share the same cached data regardless of their names.
Tap to reveal reality
Reality:Each named session caches its own data separately; sessions do not share data.
Why it matters:Misunderstanding this causes tests to reuse wrong sessions, leading to incorrect test states.
Quick: Can cy.session() cache only cookies, ignoring local storage? Commit to yes or no.
Common Belief:cy.session() caches only cookies, so local storage must be handled separately.
Tap to reveal reality
Reality:cy.session() caches cookies, local storage, and session storage together automatically.
Why it matters:Not knowing this leads to redundant code and missed optimization opportunities.
Expert Zone
1
cy.session() does not persist sessions between separate Cypress runs to maintain test isolation and avoid stale data.
2
Validation callbacks are essential for reliable session reuse, especially when sessions can expire or change during test runs.
3
Sessions are cached per unique name, so naming conventions impact test organization and caching efficiency.
When NOT to use
Avoid cy.session() when tests require fresh sessions every time to test login flows or session expiration behavior. Instead, perform full login steps in each test. Also, for very simple tests without session setup, cy.session() adds unnecessary complexity.
Production Patterns
In real projects, cy.session() is used to cache login sessions across many tests to speed up CI pipelines. Teams combine it with environment-specific credentials and validation callbacks to keep tests fast and stable. It is also used to cache other complex setup states like feature flags or user preferences.
Connections
Caching in Web Browsers
cy.session() builds on the idea of caching session data like browsers do to speed up page loads.
Understanding browser caching helps grasp how cy.session() saves and restores session state efficiently.
Test Isolation
cy.session() balances caching with test isolation by resetting sessions between runs.
Knowing test isolation principles explains why cy.session() does not persist sessions across runs.
Memory Management in Operating Systems
cy.session() stores session data in memory during test runs, similar to how OS manages temporary data.
Understanding memory caching and cleanup in OS helps appreciate cy.session() design choices for speed and reliability.
Common Pitfalls
#1Reusing a session without validation causes flaky tests when sessions expire.
Wrong approach:cy.session('user-session', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() })
Correct approach:cy.session('user-session', () => { cy.visit('/login') cy.get('#username').type('user') cy.get('#password').type('pass') cy.get('button[type=submit]').click() }, { validate() { cy.visit('/dashboard') cy.contains('Welcome') } })
Root cause:Not adding a validation callback means stale sessions are reused without checking if still valid.
#2Assuming cy.session() persists sessions between test runs leads to unexpected test failures.
Wrong approach:// Test 1 cy.session('user-session', () => { /* login */ }) // Test 2 (in a new run) cy.session('user-session') // expects session cached from Test 1
Correct approach:// Each test run must create or restore session anew cy.session('user-session', () => { /* login */ })
Root cause:Misunderstanding that cy.session() caches only in-memory per run, not across runs.
#3Using the same session name for different user roles causes incorrect test states.
Wrong approach:cy.session('user-session', () => { /* login as admin */ }) cy.session('user-session', () => { /* login as guest */ })
Correct approach:cy.session('admin-session', () => { /* login as admin */ }) cy.session('guest-session', () => { /* login as guest */ })
Root cause:Not using unique session names leads to session data overwriting and test confusion.
Key Takeaways
cy.session() caches browser session data like cookies and local storage to speed up Cypress tests by avoiding repeated setup steps.
It stores session data in memory during a test run and restores it before tests needing that session, but does not persist data between runs to keep tests isolated.
You must name sessions uniquely and provide validation callbacks to ensure sessions are valid and reused correctly.
Misunderstanding cy.session() caching scope or skipping validation leads to flaky or incorrect tests.
Using cy.session() properly improves test speed and reliability, especially for login-heavy test suites.