0
0
Cypresstesting~3 mins

Why Preserving state between tests in Cypress? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you never had to log in again for every single test you write?

The Scenario

Imagine testing a website where you must log in before each test. You open the site, enter your username and password every single time manually or write repetitive steps in your test scripts.

The Problem

This manual or repetitive approach is slow and boring. It wastes time and can cause mistakes if you forget a step or mistype credentials. It also makes tests fragile and hard to maintain.

The Solution

Preserving state between tests means saving things like login info once and reusing it automatically. This way, tests run faster and more reliably without repeating the same setup again and again.

Before vs After
Before
beforeEach(() => {
  cy.visit('/login');
  cy.get('#user').type('user');
  cy.get('#pass').type('pass');
  cy.get('#submit').click();
});
After
before(() => {
  cy.login('user', 'pass');
});

beforeEach(() => {
  cy.restoreSession();
});
What It Enables

It enables running many tests quickly and smoothly without repeating boring setup steps, making testing more efficient and fun.

Real Life Example

Think of testing an online store where you log in once, then check your cart, order history, and profile in separate tests without logging in each time.

Key Takeaways

Manual repeated setup wastes time and causes errors.

Preserving state saves login or session info once for all tests.

This makes tests faster, simpler, and easier to maintain.