0
0
Cypresstesting~15 mins

Local storage management in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - Local storage management
What is it?
Local storage management means handling the small pieces of data that a website saves in your browser. This data stays even after you close the browser, unlike temporary data. In testing, managing local storage helps check if the website saves and uses this data correctly. It involves reading, writing, and clearing this stored data during automated tests.
Why it matters
Without managing local storage in tests, we can't be sure if the website remembers user choices or login info properly. This can cause bugs that confuse users or break features. If local storage is ignored, tests might pass even when the site fails to save important data, leading to bad user experiences in real life.
Where it fits
Before learning local storage management, you should understand basic web testing and how browsers store data. After this, you can learn about session storage, cookies, and advanced state management in tests. It fits in the journey after mastering Cypress basics and before complex test data handling.
Mental Model
Core Idea
Local storage management in testing is about controlling and verifying the small, persistent data pieces a website saves in the browser to ensure correct behavior.
Think of it like...
It's like checking the notes you leave on your fridge at home. You want to make sure the right notes are there, you can add new ones, and old ones get removed when needed.
┌─────────────────────────────┐
│       Browser Storage        │
├─────────────┬───────────────┤
│ LocalStorage│ SessionStorage│
├─────────────┴───────────────┤
│  Key-Value pairs saved here  │
│  Persist after browser close │
└─────────────┬───────────────┘
              │
      ┌───────┴────────┐
      │ Cypress Test    │
      │ - Reads keys   │
      │ - Writes keys  │
      │ - Clears keys  │
      └────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is Local Storage in Browsers
🤔
Concept: Local storage is a browser feature that saves data as key-value pairs which stay even after closing the browser.
Local storage lets websites save small amounts of data on your computer. Unlike cookies, it can store more data and doesn't send it with every web request. For example, a site can save your theme preference here so it remembers it next time you visit.
Result
You understand that local storage keeps data persistently in the browser and is accessible via JavaScript.
Knowing local storage is persistent and separate from cookies helps you realize why tests must check it explicitly.
2
FoundationBasics of Cypress and Browser Storage
🤔
Concept: Cypress can interact with browser storage during tests to simulate user scenarios and verify data.
Cypress runs tests inside the browser, so it can read and write local storage using commands like cy.window() or cy.clearLocalStorage(). This allows tests to set up or check stored data before or after actions.
Result
You can access and manipulate local storage in Cypress tests to control test conditions.
Understanding Cypress runs in the browser context is key to managing local storage effectively.
3
IntermediateReading and Writing Local Storage in Tests
🤔Before reading on: do you think Cypress has direct commands to get and set local storage items, or do you need to use JavaScript inside tests? Commit to your answer.
Concept: Cypress uses JavaScript commands inside tests to read and write local storage items.
To write: use cy.window().then(win => win.localStorage.setItem('key', 'value')) To read: use cy.window().then(win => { const value = win.localStorage.getItem('key') expect(value).to.equal('expected') }) This lets tests verify stored data matches expectations.
Result
Tests can confirm that local storage contains the right data after user actions.
Knowing you must use cy.window() to access local storage clarifies how Cypress interacts with browser APIs.
4
IntermediateClearing Local Storage Between Tests
🤔Before reading on: do you think local storage clears automatically between Cypress tests, or do you need to clear it manually? Commit to your answer.
Concept: Local storage does not clear automatically between tests; you must clear it to avoid test interference.
Use cy.clearLocalStorage() in beforeEach() hooks to clear storage before each test. This prevents leftover data from one test affecting another, ensuring tests are independent and reliable.
Result
Tests run with a clean local storage state, avoiding false passes or failures.
Understanding test isolation prevents flaky tests caused by leftover data.
5
IntermediateUsing Cypress Commands to Manage Local Storage
🤔
Concept: You can create custom Cypress commands to simplify local storage management across tests.
Example: Cypress.Commands.add('setLocalStorage', (key, value) => { cy.window().then(win => win.localStorage.setItem(key, value)) }) Then in tests: cy.setLocalStorage('token', 'abc123') This makes tests cleaner and reusable.
Result
Tests become easier to write and maintain with reusable commands.
Knowing how to extend Cypress with custom commands improves test code quality and reduces repetition.
6
AdvancedPreserving Local Storage Across Tests
🤔Before reading on: do you think local storage is shared automatically across all tests in Cypress, or do you need special handling to preserve it? Commit to your answer.
Concept: Local storage resets between tests by default; you can preserve it manually to simulate continuous sessions.
Use plugins or write code to save local storage before a test ends and restore it before the next test starts. For example, use before() and after() hooks to save and restore local storage JSON. This simulates a user staying logged in across tests.
Result
Tests can simulate persistent user sessions or states across multiple test cases.
Knowing how to preserve local storage helps test flows that span multiple pages or sessions.
7
ExpertHandling Local Storage in Parallel and CI Environments
🤔Before reading on: do you think local storage behaves the same in local runs and CI pipelines with parallel tests? Commit to your answer.
Concept: Local storage is browser-specific and isolated per test runner instance; parallel tests require careful management to avoid conflicts.
In CI with parallel runs, each test runs in a separate browser instance with its own local storage. Tests must not rely on shared local storage state. Use unique keys or clear storage properly. Also, some CI browsers may have storage limits or quirks to handle.
Result
Tests remain reliable and independent even when run in parallel or CI environments.
Understanding environment differences prevents flaky tests and data leaks in automated pipelines.
Under the Hood
Local storage is a simple key-value store inside the browser, accessible via JavaScript's window.localStorage object. It stores strings only and persists data on disk until explicitly cleared. Cypress runs tests inside the browser context, so it accesses local storage through the window object. Commands like cy.window() provide access to this object, allowing tests to read or write data. Local storage is isolated per browser profile, so each test run has its own storage unless preserved manually.
Why designed this way?
Local storage was designed to provide a simple, persistent client-side storage without the overhead of cookies or server calls. It stores only strings to keep the API simple and fast. Cypress accesses it via the browser's window object to mimic real user interactions closely. This design avoids complex APIs and keeps tests realistic by running inside the actual browser environment.
┌───────────────┐       ┌───────────────┐
│ Cypress Test  │──────▶│ Browser Window│
│ (cy.window()) │       │ (localStorage)│
└───────────────┘       └───────┬───────┘
                                  │
                      ┌───────────┴───────────┐
                      │ Persistent Key-Value  │
                      │ Storage on Disk       │
                      └───────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does clearing cookies also clear local storage? Commit to yes or no before reading on.
Common Belief:Clearing cookies also clears local storage automatically.
Tap to reveal reality
Reality:Cookies and local storage are separate; clearing cookies does not clear local storage.
Why it matters:Tests that clear cookies but not local storage may have leftover data causing unexpected test results.
Quick: Is local storage shared across different browser tabs automatically? Commit to yes or no before reading on.
Common Belief:Local storage is shared instantly across all tabs of the same site.
Tap to reveal reality
Reality:Local storage is shared per origin but changes are not automatically synchronized across tabs without reload or events.
Why it matters:Tests assuming instant sync may fail or behave inconsistently when simulating multi-tab scenarios.
Quick: Does Cypress automatically preserve local storage between tests? Commit to yes or no before reading on.
Common Belief:Cypress keeps local storage intact between tests by default.
Tap to reveal reality
Reality:Cypress clears local storage between tests unless you explicitly preserve or restore it.
Why it matters:Tests relying on persistent local storage without setup will fail or produce flaky results.
Quick: Can local storage store complex objects directly? Commit to yes or no before reading on.
Common Belief:You can store JavaScript objects directly in local storage without conversion.
Tap to reveal reality
Reality:Local storage stores only strings; objects must be converted to strings (e.g., JSON) before storing.
Why it matters:Failing to convert objects leads to storing '[object Object]' strings, causing bugs in tests and apps.
Expert Zone
1
Local storage size limits vary by browser and can cause silent failures if exceeded, which tests should detect.
2
Some browsers clear local storage on private/incognito mode exit, affecting test repeatability.
3
Race conditions can occur if tests read local storage before the app finishes writing, requiring careful timing or retries.
When NOT to use
Local storage is not suitable for sensitive data like passwords or tokens because it is accessible by any script on the page. Use secure HTTP-only cookies or server-side sessions instead. Also, for temporary data that should clear on tab close, session storage is better.
Production Patterns
In real-world tests, local storage management is used to simulate logged-in users by setting auth tokens directly, speeding up tests. Teams create custom Cypress commands to handle storage consistently. Preservation of local storage is common in multi-step flows to avoid repeated logins. Tests also verify that local storage updates correctly after user actions to catch bugs early.
Connections
Cookies
Related browser storage mechanisms with different scopes and lifetimes
Understanding local storage alongside cookies helps testers choose the right storage to verify and manipulate for different test scenarios.
State Management in Frontend Frameworks
Builds-on local storage as a persistence layer for app state
Knowing how local storage works clarifies how frameworks save user preferences or session data beyond page reloads.
Database Transactions
Similar pattern of managing persistent state with atomic operations
Local storage management in tests parallels ensuring data consistency in databases, teaching the importance of state isolation and cleanup.
Common Pitfalls
#1Not clearing local storage between tests causes data leakage.
Wrong approach:describe('Test suite', () => { it('Test 1', () => { // test code }) it('Test 2', () => { // test code }) })
Correct approach:describe('Test suite', () => { beforeEach(() => { cy.clearLocalStorage() }) it('Test 1', () => { // test code }) it('Test 2', () => { // test code }) })
Root cause:Assuming Cypress resets local storage automatically between tests.
#2Storing objects directly without stringifying causes wrong data storage.
Wrong approach:cy.window().then(win => win.localStorage.setItem('user', {name: 'Alice'}))
Correct approach:cy.window().then(win => win.localStorage.setItem('user', JSON.stringify({name: 'Alice'})))
Root cause:Not knowing local storage only stores strings, so objects must be converted.
#3Trying to read local storage without waiting for the app to set it causes flaky tests.
Wrong approach:cy.window().then(win => { const token = win.localStorage.getItem('token') expect(token).to.exist })
Correct approach:cy.wait(500) // wait for app to set token cy.window().then(win => { const token = win.localStorage.getItem('token') expect(token).to.exist })
Root cause:Not synchronizing test timing with app state changes.
Key Takeaways
Local storage is a persistent browser feature that stores key-value pairs as strings, surviving browser restarts.
Cypress accesses local storage through the browser's window object, requiring explicit commands to read, write, or clear it.
Tests must clear or manage local storage between runs to avoid interference and flaky results.
Local storage is not automatically shared or preserved between tests or tabs without special handling.
Proper local storage management in tests improves reliability and simulates real user scenarios like logged-in sessions.