Skip to main content

Using JavaScript localStorage Property in Cypress

You can use JavaScript localStorage property of the window interface in Cypress to access the browser's localStorage object. 

Syntax

window.localStorage
localStorage

You can access localStorage methods with windows. or without using it.

Methods

  1. setItem(key, value):  store key/value pair.
  2. getItem(key): get the value by key.
  3. removeItem(key): remove the key with its value.
  4. clear(): delete everything.
  5. key(index): get the key on a given position.
  6. length(): the number of stored items.

Examples

Demo Website: http://autopract.com/

Using JavaScript localStorage in Cypress

Using length and key Method

it.only('Verify local storage', () => {
    cy.visit('http://www.autopract.com/#/home/fashion')

    cy.get("button[aria-label='Close'] ")
        .click()
        .then(() => {
            // Count no of localStorge items
            cy.log(localStorage.length)
            
            // Print Key name in logs
            for (var i = 0; i < localStorage.length; i++) {
                cy.log(localStorage.key(i))
            }
        })
})

Using length and key Method

Using Get Item and Set Item

it.only('Verify local storage', () => {
    cy.visit('http://www.autopract.com/#/home/fashion')

    cy.get("button[aria-label='Close'] ")
        .click()
        .then(() => {
            // Assert value of newsletter is ture
            expect(localStorage.getItem('newsletter')).to.equal('true')
            
            // Create new key with value
            window.localStorage.setItem('mykey', 'hello world')
        })
})

Using Get Item and Set Item

Using remove item and clear method

it.only('Verify local storage', () => {
    cy.visit('http://www.autopract.com/#/home/fashion')

    cy.get("button[aria-label='Close'] ").click()

   // clear newletter item from localstorage
    cy.wait(10000).then(() => {
        localStorage.removeItem('newsletter')
    })
    
   // clear all items from local storage
    cy.wait(10000).then(() => {
        localStorage.clear()
    })
})

Wait added just to see the output in Console. 

Video Tutorial: Cypress Access the Local Storage

Tags
Submitted by tgoswami on June 10, 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.