0
0
Cypresstesting~5 mins

Local storage management in Cypress

Choose your learning style9 modes available
Introduction

Local storage lets websites save small bits of data on your browser. Managing it in tests helps check if data is saved or cleared correctly.

When you want to test if a website saves user preferences locally.
When you need to clear saved data before starting a new test.
When you want to check if data is correctly removed after logout.
When testing if local storage updates after certain actions.
When verifying that local storage data persists after page reload.
Syntax
Cypress
cy.window().then(win => {
  // Get local storage item
  const item = win.localStorage.getItem('key')

  // Set local storage item
  win.localStorage.setItem('key', 'value')

  // Remove local storage item
  win.localStorage.removeItem('key')

  // Clear all local storage
  win.localStorage.clear()
})

Use cy.window() to access the browser's window object where local storage lives.

Always perform local storage actions inside then() to ensure Cypress waits for the window object.

Examples
This saves the value 'dark' under the key 'theme' in local storage.
Cypress
cy.window().then(win => {
  win.localStorage.setItem('theme', 'dark')
})
This reads the 'theme' value and checks if it equals 'dark'.
Cypress
cy.window().then(win => {
  const theme = win.localStorage.getItem('theme')
  expect(theme).to.equal('dark')
})
This removes the 'theme' item from local storage.
Cypress
cy.window().then(win => {
  win.localStorage.removeItem('theme')
})
This clears all items from local storage.
Cypress
cy.window().then(win => {
  win.localStorage.clear()
})
Sample Program

This test visits a page, saves a local storage item, checks it, removes it, and confirms it is gone.

Cypress
describe('Local Storage Management Test', () => {
  it('should save, read, and clear local storage', () => {
    cy.visit('https://example.cypress.io')

    // Save item
    cy.window().then(win => {
      win.localStorage.setItem('user', 'Alice')
    })

    // Check saved item
    cy.window().then(win => {
      const user = win.localStorage.getItem('user')
      expect(user).to.equal('Alice')
    })

    // Remove item
    cy.window().then(win => {
      win.localStorage.removeItem('user')
    })

    // Confirm removal
    cy.window().then(win => {
      const user = win.localStorage.getItem('user')
      expect(user).to.be.null
    })
  })
})
OutputSuccess
Important Notes

Local storage is shared per domain, so tests on different sites have separate storage.

Use cy.clearLocalStorage() as a shortcut to clear storage if preferred.

Remember local storage stores only strings, so convert objects with JSON.stringify() and JSON.parse().

Summary

Local storage holds small data in the browser for a website.

Cypress uses cy.window() to access and manage local storage.

Tests can save, read, remove, and clear local storage to check app behavior.