0
0
Cypresstesting~3 mins

Why cy.session() for session caching in Cypress? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could skip logging in every time and save minutes on every test run?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
beforeEach(() => {
  cy.visit('/login')
  cy.get('#user').type('user')
  cy.get('#pass').type('pass')
  cy.get('button').click()
})
After
beforeEach(() => {
  cy.session('userSession', () => {
    cy.visit('/login')
    cy.get('#user').type('user')
    cy.get('#pass').type('pass')
    cy.get('button').click()
  })
})
What It Enables

You can run many tests quickly and confidently because the login session is cached and reused automatically.

Real Life Example

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.

Key Takeaways

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.