Bird
Raised Fist0
Cypresstesting~15 mins

Local storage management in Cypress - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the primary purpose of local storage in a web browser when testing with Cypress?
easy
A. To run JavaScript code on the server
B. To store small amounts of data persistently for a website
C. To style the webpage dynamically
D. To manage network requests

Solution

  1. Step 1: Understand local storage role

    Local storage is used by browsers to save small data like user preferences or tokens persistently.
  2. Step 2: Connect with Cypress testing

    Cypress can access this storage to verify or manipulate data during tests.
  3. Final Answer:

    To store small amounts of data persistently for a website -> Option B
  4. Quick Check:

    Local storage = persistent small data [OK]
Hint: Local storage saves small data for the site, not server tasks [OK]
Common Mistakes:
  • Confusing local storage with server-side storage
  • Thinking local storage runs code
  • Mixing local storage with styling or network
2. Which Cypress command is used to access the browser's window object to manage local storage?
easy
A. cy.document()
B. cy.getLocalStorage()
C. cy.localStorage()
D. cy.window()

Solution

  1. Step 1: Recall Cypress commands for browser objects

    To access the browser's window object, Cypress provides cy.window().
  2. Step 2: Understand local storage access

    Local storage is a property of the window object, so cy.window() is used to reach it.
  3. Final Answer:

    cy.window() -> Option D
  4. Quick Check:

    Access window with cy.window() [OK]
Hint: Use cy.window() to reach local storage via window object [OK]
Common Mistakes:
  • Using non-existent commands like cy.getLocalStorage()
  • Confusing cy.document() with window object
  • Assuming cy.localStorage() exists
3. What will be the output of the following Cypress code snippet?
cy.window().then(win => {
  win.localStorage.setItem('user', 'Alice');
  const user = win.localStorage.getItem('user');
  cy.wrap(user).should('equal', 'Alice');
});
medium
A. Test will fail due to syntax error in setItem usage
B. Test will fail because localStorage is not accessible
C. Test will pass because 'user' is set and retrieved correctly
D. Test will pass but 'user' will be undefined

Solution

  1. Step 1: Analyze localStorage set and get

    The code sets 'user' key to 'Alice' in localStorage, then retrieves it correctly.
  2. Step 2: Check assertion correctness

    The assertion checks if retrieved value equals 'Alice', which is true, so test passes.
  3. Final Answer:

    Test will pass because 'user' is set and retrieved correctly -> Option C
  4. Quick Check:

    Set and get localStorage works, test passes [OK]
Hint: Setting then getting localStorage key returns correct value [OK]
Common Mistakes:
  • Assuming localStorage is inaccessible in Cypress
  • Thinking setItem syntax is wrong
  • Expecting undefined instead of stored value
4. Identify the error in this Cypress code that tries to clear local storage:
cy.window().then(win => {
  win.localStorage.clear;
});
medium
A. Missing parentheses to call clear method
B. localStorage.clear requires a key argument
C. cy.window() cannot access localStorage
D. clear is not a function of localStorage

Solution

  1. Step 1: Check localStorage clear usage

    localStorage.clear is a function and must be called with parentheses: clear()
  2. Step 2: Identify missing parentheses error

    The code uses clear without parentheses, so it does not execute the function.
  3. Final Answer:

    Missing parentheses to call clear method -> Option A
  4. Quick Check:

    Call clear() with parentheses to clear storage [OK]
Hint: Always add () to call localStorage.clear() method [OK]
Common Mistakes:
  • Forgetting parentheses when calling functions
  • Thinking clear needs a key argument
  • Assuming cy.window() can't access localStorage
5. You want to write a Cypress test that saves a token in local storage, reloads the page, and then verifies the token is still present. Which sequence of commands correctly achieves this?
hard
A. cy.window().then(win => win.localStorage.setItem('token', 'abc123')); cy.reload(); cy.window().then(win => expect(win.localStorage.getItem('token')).to.equal('abc123'));
B. cy.setLocalStorage('token', 'abc123'); cy.reload(); cy.getLocalStorage('token').should('equal', 'abc123');
C. cy.window().then(win => win.localStorage.setItem('token', 'abc123')); cy.reload(); cy.window().its('localStorage.token').should('equal', 'abc123');
D. cy.window().then(win => win.localStorage.clear()); cy.reload(); cy.window().its('localStorage.token').should('be.null');

Solution

  1. Step 1: Save token in localStorage correctly

    Using cy.window().then(win => win.localStorage.setItem('token', 'abc123')) correctly sets the token.
  2. Step 2: Reload and verify token presence

    After cy.reload(), accessing localStorage via cy.window().then and asserting with expect ensures token is still 'abc123'.
  3. Step 3: Evaluate other options

    cy.window().then(win => win.localStorage.setItem('token', 'abc123')); cy.reload(); cy.window().its('localStorage.token').should('equal', 'abc123'); uses incorrect property access for localStorage token; cy.setLocalStorage('token', 'abc123'); cy.reload(); cy.getLocalStorage('token').should('equal', 'abc123'); uses non-existent commands; cy.window().then(win => win.localStorage.clear()); cy.reload(); cy.window().its('localStorage.token').should('be.null'); clears storage and checks for null, which is not the goal.
  4. Final Answer:

    Use cy.window() to set, reload, then check with expect -> Option A
  5. Quick Check:

    Set, reload, then assert with cy.window() and expect [OK]
Hint: Set token, reload, then check with cy.window() and expect [OK]
Common Mistakes:
  • Using wrong localStorage property access
  • Using non-existent Cypress commands
  • Clearing storage instead of verifying token
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard