Skip to main content

Cypress localStorage Commands

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.

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/commands.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.

Example 

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

Demo Link: http://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

Video Tutorial: Cypress Local Storage Commands

Tags
Submitted by tgoswami on June 15, 2021

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.