Cypress clearLocalStorage Command

Profile picture for user arilio666

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.