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
- Install Local Storage plugin
- Local Storage Methods
- Demo Website
- Cypress Get Local Storage
- Cypress Set Local Storage
- Remove Local Storage Item
- 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:
- cy.getLocalStorage(item): Gets localStorage item.
- cy.setLocalStorage(item, value): Sets localStorage item.
- cy.removeLocalStorage(item): Removes localStorage item.
- cy.saveLocalStorage([snapshotName]): It saves current local storage values in to an internal snapshot.
- cy.restoreLocalStorage([snapshotName]): Restores local Storage to previously snapshot saved values.
- cy.clearLocalStorageSnapshot([snapshotName]): Clear local storage snapshot values.
- 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 Link: http://autopract.com/selenium/localstorage.html
Snapshot of local storage After clicking on Add Item 1 and 2 button
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.
- Log in to post comments