How to Get Elements From Local Storage in Cypress
To get elements from the local storage in Cypress, we can simply use the local storage API as we would elsewhere:
Copied to clipboard!
expect(localStorage.getItem('token')).to.eq('123');
expect(localStorage.getItem('cookie')).to.eq('πͺ');
To verify elements inside the local storage after a user action has taken place, we can also attach a should
callback to the user event and do the verifications inside the callback function:
Copied to clipboard!
cy.get('.login').click().should(() => {
expect(localStorage.getItem('token')).to.eq('123');
expect(localStorage.getItem('cookie')).to.eq('πͺ');
});
Cypress also exposes a clearLocalStorage
function that we can use to clear everything from the local storage and work with a fresh, new state:
Copied to clipboard!
cy.clearLocalStorage().should(localStorage => {
expect(localStorage.getItem('token')).to.be.null;
expect(localStorage.getItem('cookie')).to.be.null;
});
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews