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
- setItem(key, value): store key/value pair.
- getItem(key): get the value by key.
- removeItem(key): remove the key with its value.
- clear(): delete everything.
- key(index): get the key on a given position.
- length(): the number of stored items.
Examples
Demo Website: http://autopract.com/
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 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 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.
Tags