cy.session() helps save time by remembering login or setup steps so tests run faster and more reliably.
0
0
cy.session() for session caching in Cypress
Introduction
When you want to avoid logging in before every test to save time.
When your tests need the same user session repeatedly.
When you want to reduce flaky tests caused by repeated setup steps.
When you want to speed up end-to-end tests by caching session data.
When you want to isolate tests but keep session state consistent.
Syntax
Cypress
cy.session(sessionId, setupCallback, options?)
sessionId: A unique name or key for the session.
setupCallback: A function that performs login or setup steps.
Examples
This caches a session named 'user1' by logging in once.
Cypress
cy.session('user1', () => { cy.visit('/login') cy.get('#username').type('user1') cy.get('#password').type('password') cy.get('button[type=submit]').click() })
This caches a session named 'admin' using an API login request.
Cypress
cy.session('admin', () => { cy.request('POST', '/api/login', { username: 'admin', password: 'adminpass' }) })
Sample Program
This test suite uses cy.session() to cache the login session for 'standardUser'. The login runs only once before all tests, making tests faster and stable.
Cypress
describe('Test with session caching', () => { beforeEach(() => { cy.session('standardUser', () => { cy.visit('/login') cy.get('#username').type('standardUser') cy.get('#password').type('password123') cy.get('button[type=submit]').click() cy.url().should('include', '/dashboard') }) }) it('should show user dashboard', () => { cy.visit('/dashboard') cy.contains('Welcome, standardUser').should('be.visible') }) it('should allow user to logout', () => { cy.visit('/dashboard') cy.get('#logout').click() cy.url().should('include', '/login') }) })
OutputSuccess
Important Notes
Use unique session IDs to avoid conflicts between different users or setups.
Sessions are automatically restored between tests, so you don't need to repeat login steps.
cy.session() improves test speed and reduces flakiness by caching browser state.
Summary
cy.session() caches login or setup steps to speed up tests.
Use it when you want to reuse user sessions across tests.
It makes tests faster and more reliable by avoiding repeated logins.