
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:
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:
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:
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:

Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: