Bird
Raised Fist0
Cypresstesting~15 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using cy.session() in Cypress tests?
easy
A. To run tests in parallel
B. To clear cookies before each test
C. To cache user sessions and avoid repeated login steps
D. To generate random test data

Solution

  1. Step 1: Understand what cy.session() does

    cy.session() caches login or setup steps so tests don't repeat them.
  2. Step 2: Identify the main benefit

    This caching speeds up tests by reusing sessions instead of logging in every time.
  3. Final Answer:

    To cache user sessions and avoid repeated login steps -> Option C
  4. Quick Check:

    Session caching = Avoid repeated logins [OK]
Hint: Remember: cy.session() saves login to speed tests [OK]
Common Mistakes:
  • Thinking it clears cookies instead of caching sessions
  • Confusing it with parallel test execution
  • Assuming it generates test data
2. Which of the following is the correct syntax to create a session with cy.session()?
easy
A. cy.session('user', () => { cy.login() })
B. cy.session('user', cy.login())
C. cy.session('user', function cy.login())
D. cy.session('user', cy.login)

Solution

  1. Step 1: Recall cy.session() syntax

    The second argument must be a callback function that runs login steps, e.g., () => { cy.login() }.
  2. Step 2: Check each option

    Only cy.session('user', () => { cy.login() }) correctly passes a callback function. The other options pass a function reference incorrectly, execute the function immediately, or use invalid syntax.
  3. Final Answer:

    cy.session('user', () => { cy.login() }) -> Option A
  4. Quick Check:

    Callback function syntax = cy.session('user', () => { cy.login() }) [OK]
Hint: Use arrow function for session callback: () => { ... } [OK]
Common Mistakes:
  • Passing function call instead of function
  • Using invalid function syntax
  • Omitting the callback wrapper
3. Given the code below, what will be the output in the test run?
cy.session('admin', () => {
  cy.visit('/login')
  cy.get('#username').type('admin')
  cy.get('#password').type('password')
  cy.get('button[type=submit]').click()
})

cy.session('admin', () => {
  cy.visit('/dashboard')
})
medium
A. The login steps run only once; second session reuses cached login
B. Both sessions run login steps twice
C. Second session throws an error because visit is different
D. The test fails due to duplicate session keys

Solution

  1. Step 1: Understand session caching behavior

    Sessions with the same key ('admin') cache the first login steps and reuse them in subsequent calls.
  2. Step 2: Analyze the second cy.session() call

    The second call with the same key skips login steps and reuses the cached session, so only the visit to '/dashboard' runs.
  3. Final Answer:

    The login steps run only once; second session reuses cached login -> Option A
  4. Quick Check:

    Same key session = cached login reused [OK]
Hint: Same session key means login runs once only [OK]
Common Mistakes:
  • Assuming login runs every time
  • Thinking different visits cause errors
  • Believing duplicate keys cause test failure
4. Identify the error in the following code using cy.session():
cy.session('user', () => {
  cy.visit('/login')
  cy.get('#user').type('test')
  cy.get('#pass').type('1234')
  cy.get('button').click()
})

cy.session('user', () => {
  cy.visit('/profile')
})
medium
A. The session key 'user' is reused, causing session cache conflict
B. The login callback does not return a promise or chain commands
C. The second session callback should include login steps again
D. No error; code works as expected

Solution

  1. Step 1: Check session key usage

    Reusing the same session key 'user' is correct to cache and reuse the session.
  2. Step 2: Verify callback structure

    The callback contains Cypress commands chained properly; no need to return a promise explicitly.
  3. Step 3: Confirm second session usage

    The second session call reuses the cached session and visits '/profile' without error.
  4. Final Answer:

    No error; code works as expected -> Option D
  5. Quick Check:

    Reusing session key with proper callback = No error [OK]
Hint: Reusing session key with proper callback is valid [OK]
Common Mistakes:
  • Thinking session keys must be unique per call
  • Expecting explicit promise return in callback
  • Assuming login steps must repeat every time
5. You want to speed up tests by caching sessions but notice some tests fail intermittently due to stale session data. How can you modify cy.session() usage to fix this?
hard
A. Use a different session key for every test to avoid caching
B. Add a validate callback to check session validity before reuse
C. Remove cy.session() and login every time
D. Clear cookies manually before each test instead of using cy.session()

Solution

  1. Step 1: Understand stale session problem

    Stale sessions cause intermittent failures because cached data may expire or become invalid.
  2. Step 2: Use validate callback in cy.session()

    The validate callback runs before reusing a session to confirm it is still valid, forcing a fresh login if needed.
  3. Step 3: Avoid other options

    Using different keys disables caching, removing benefits. Removing cy.session() slows tests. Clearing cookies manually is less efficient.
  4. Final Answer:

    Add a validate callback to check session validity before reuse -> Option B
  5. Quick Check:

    Validate callback fixes stale session issues [OK]
Hint: Use validate callback to confirm session freshness [OK]
Common Mistakes:
  • Disabling caching by changing keys unnecessarily
  • Ignoring session validation causing flaky tests
  • Removing session caching and slowing tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard