How to Get Elements From Local Storage in Cypress

How to Get Elements From Local Storage in Cypress

Ferenc Almasi β€’ 2021 October 21 β€’ Read time 1 min read
  • twitter
  • facebook

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;
});
The callback function yields the local storage object

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Get Elements From Local Storage in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.