Cypress localStorage Commands

Profile picture for user devraj

If you want to preserve local storage between Cypress tests or disable local storage to check error handling. You can extend Cypress Cy commands using the localStorage commands plugin. 

This plugin allows you to use all browser local Storage methods through the cypress command.

Table of Content

  1. Install Local Storage plugin
  2. Local Storage Methods
  3. Demo Website
  4. Cypress Get Local Storage
  5. Cypress Set Local Storage
  6. Remove Local Storage Item
  7. Video Tutorial

Install Plugin

You can install this module using NPM using the below steps:

Step 1: Install using NPM

$ npm i --save-dev cypress-localstorage-commands

Step 2: Add below line to cypress/support/e2e.js

import "cypress-localstorage-commands"

TypeScript

For typescript add following code in tsconfig.json

{
  "compilerOptions": {
    "types": ["cypress", "cypress-localstorage-commands"]
  }
}

To reference the package use below line

/// <reference types="cypress-localstorage-commands" />

Methods

You can use following 7 methods after installing this plugin:

  1. cy.getLocalStorage(item): Gets localStorage item.
  2. cy.setLocalStorage(item, value): Sets localStorage item.
  3. cy.removeLocalStorage(item): Removes localStorage item.
  4. cy.saveLocalStorage([snapshotName]): It saves current local storage values in to an internal snapshot.
  5. cy.restoreLocalStorage([snapshotName]): Restores local Storage to previously snapshot saved values.
  6. cy.clearLocalStorageSnapshot([snapshotName]): Clear local storage snapshot values.
  7. cy.disableLocalStorage(options): Disables localStorage.

Demo Website

In this article we will discuss first 3 methods, remaining 4 we will demo in other article.

Demo Linkhttp://autopract.com/selenium/localstorage.html

Snapshot of local storage After clicking on Add Item 1 and 2 button

Cypress localStorage Commands

Item 1 and 2 are added with value Hello and World.

Use get Local Storage to get items

it.only('Verify local storage', () => {
    cy.visit('http://autopract.com/selenium/localstorage.html').then(() => {
    cy.get('#set-local-storage1').click()
    cy.get('#set-local-storage2')
        .click()
        .then(() => {
            cy.getLocalStorage('item1').should('equal', 'hello')
            cy.getLocalStorage('item2').should('equal', 'world')
        })
    })
})

Use set Local Storage to add new item

cy.setLocalStorage('item3', 'MyValue')

This will add item3 in local storage with value MyValue.

Remove item from Local Storage

cy.removeLocalStorage('item1')

this will remove item1 from storage.

Output

Output after adding item3 and removing item1.

cypress add remove item from local storage