cy.session() for session caching in Cypress - Build an Automation Script
describe('Login with session caching using cy.session()', () => { const username = 'testuser'; const password = 'Test@1234'; function login() { cy.visit('/login'); cy.get('#username').type(username); cy.get('#password').type(password); cy.get('#loginBtn').click(); cy.url().should('include', '/dashboard'); } beforeEach(() => { cy.session('user-session', login); }); it('should login and cache session', () => { // Session is created in beforeEach cy.visit('/dashboard'); cy.url().should('include', '/dashboard'); cy.get('#logoutBtn').should('be.visible'); }); it('should logout and require login again', () => { cy.visit('/dashboard'); cy.get('#logoutBtn').click(); cy.url().should('include', '/login'); // After logout, session should be cleared cy.session('user-session', login, { cacheAcrossSpecs: false }); }); });
The test suite uses cy.session() to cache the login session under the name 'user-session'.
The login function performs the login steps: visiting the login page, entering credentials, clicking login, and verifying the dashboard URL.
In beforeEach, cy.session() runs the login function only if the session is not cached, speeding up tests by reusing the session.
The first test verifies that after session caching, visiting '/dashboard' shows the dashboard page and logout button.
The second test logs out by clicking the logout button, verifies the URL returns to '/login', and clears the session cache to ensure login is required again.
Selectors use stable IDs, and assertions check URL and element visibility to confirm correct behavior.
Now add data-driven testing with 3 different sets of valid user credentials using cy.session()
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
