What if you could skip logging in every time and save minutes on every test run?
Why cy.session() for session caching in Cypress? - Purpose & Use Cases
Imagine you are testing a website that requires logging in before each test. You open the browser, enter your username and password, wait for the page to load, and then start testing. You repeat this for every single test manually or by writing the same login steps again and again.
This manual approach is slow because logging in takes time. It is also error-prone since typing mistakes or network delays can cause tests to fail. Repeating the same steps wastes time and makes your tests longer and harder to maintain.
Using cy.session() lets you save the login session once and reuse it for all tests. This means Cypress remembers you are logged in without repeating the login steps every time. Your tests run faster, are more reliable, and easier to write.
beforeEach(() => {
cy.visit('/login')
cy.get('#user').type('user')
cy.get('#pass').type('pass')
cy.get('button').click()
})beforeEach(() => {
cy.session('userSession', () => {
cy.visit('/login')
cy.get('#user').type('user')
cy.get('#pass').type('pass')
cy.get('button').click()
})
})You can run many tests quickly and confidently because the login session is cached and reused automatically.
For example, an e-commerce site test suite logs in once with cy.session() and then tests adding items to the cart, checking out, and viewing order history without logging in again.
Manual login before each test is slow and fragile.
cy.session() caches login sessions to speed up tests.
This makes tests faster, more reliable, and easier to maintain.
Practice
cy.session() in Cypress tests?Solution
Step 1: Understand what
cy.session()doescy.session()caches login or setup steps so tests don't repeat them.Step 2: Identify the main benefit
This caching speeds up tests by reusing sessions instead of logging in every time.Final Answer:
To cache user sessions and avoid repeated login steps -> Option CQuick Check:
Session caching = Avoid repeated logins [OK]
cy.session() saves login to speed tests [OK]- Thinking it clears cookies instead of caching sessions
- Confusing it with parallel test execution
- Assuming it generates test data
cy.session()?Solution
Step 1: Recall
The second argument must be a callback function that runs login steps, e.g.,cy.session()syntax() => { cy.login() }.Step 2: Check each option
Onlycy.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.Final Answer:
cy.session('user', () => { cy.login() }) -> Option AQuick Check:
Callback function syntax = cy.session('user', () => { cy.login() }) [OK]
- Passing function call instead of function
- Using invalid function syntax
- Omitting the callback wrapper
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')
})Solution
Step 1: Understand session caching behavior
Sessions with the same key ('admin') cache the first login steps and reuse them in subsequent calls.Step 2: Analyze the second
The second call with the same key skips login steps and reuses the cached session, so only the visit to '/dashboard' runs.cy.session()callFinal Answer:
The login steps run only once; second session reuses cached login -> Option AQuick Check:
Same key session = cached login reused [OK]
- Assuming login runs every time
- Thinking different visits cause errors
- Believing duplicate keys cause test failure
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')
})Solution
Step 1: Check session key usage
Reusing the same session key 'user' is correct to cache and reuse the session.Step 2: Verify callback structure
The callback contains Cypress commands chained properly; no need to return a promise explicitly.Step 3: Confirm second session usage
The second session call reuses the cached session and visits '/profile' without error.Final Answer:
No error; code works as expected -> Option DQuick Check:
Reusing session key with proper callback = No error [OK]
- Thinking session keys must be unique per call
- Expecting explicit promise return in callback
- Assuming login steps must repeat every time
cy.session() usage to fix this?Solution
Step 1: Understand stale session problem
Stale sessions cause intermittent failures because cached data may expire or become invalid.Step 2: Use
Thevalidatecallback incy.session()validatecallback runs before reusing a session to confirm it is still valid, forcing a fresh login if needed.Step 3: Avoid other options
Using different keys disables caching, removing benefits. Removingcy.session()slows tests. Clearing cookies manually is less efficient.Final Answer:
Add avalidatecallback to check session validity before reuse -> Option BQuick Check:
Validate callback fixes stale session issues [OK]
- Disabling caching by changing keys unnecessarily
- Ignoring session validation causing flaky tests
- Removing session caching and slowing tests
Ready to prove it?
Pass the test and this pattern moves unknown
