Skip to main content

Cypress clearLocalStorage Command

clearLocalStorage in Cypress clears data in local storage for current domain and subdomain.

Cypress automatically runs this command before each test to prevent the state from being shared across tests, so it is unnecessary to use it unless the goal is to clear local storage inside a single test.

Syntax

cy.clearLocalStorage()
cy.clearLocalStorage(key)
cy.clearLocalStorage(options)
cy.clearLocalStorage(key, options)

Arguments Used In clearLocalStorage

  1. Options: Pass in the options object to change the default behavior of cy.clearLocalStorage().
    • Log: Displays the command in the command log, and the default value is true.
  2. Key: Specify key to be cleared in local storage.

Rules For Using clearLocalStorage

  1. cy.clearLocalStorage() must be chained off of cy.
  2. cy.clearLocalStorage() cannot have any assertions chained to it.
  3. cy.clearLocalStorage() should never time out.

Note: cy.clearLocalStorage() yields null and cannot be chained further.

Examples

Demo Link: http://autopract.com/

Cypress Clear LocalStorage

Clear All Local Storage

This will delete all the items.

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

    cy.get("button[aria-label='Close'] ")
        .click()
        .then(() => {
            cy.clearLocalStorage()
        })
})

Clear Local Storage with Key 

    cy.clearLocalStorage('newsletter')

    This will also delete newsletter key.

    Clear Local Storage with Key Regex 

    cy.clearLocalStorage(/new*/)

    This will also delete newsletter key. 

      Conclusion:

      So using this command is optional depending on the test it is being used on.

      Video Tutorial: Cypress Clear Browser Local Storage

      Tags
      Submitted by arilio666 on April 20, 2022

      Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

      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.