How to mock localStorage in JavaScript unit tests?

Anthony Sottile picture Anthony Sottile · Jul 14, 2012 · Viewed 82k times · Source

Are there any libraries out there to mock localStorage?

I've been using Sinon.JS for most of my other javascript mocking and have found it is really great.

My initial testing shows that localStorage refuses to be assignable in firefox (sadface) so I'll probably need some sort of hack around this :/

My options as of now (as I see) are as follows:

  1. Create wrapping functions that all my code uses and mock those
  2. Create some sort of (might be complicated) state management (snapshot localStorage before test, in cleanup restore snapshot) for localStorage.
  3. ??????

What do you think of these approaches and do you think there are any other better ways to go about this? Either way I'll put the resulting "library" that I end up making on github for open source goodness.

Answer

Andreas Köberle picture Andreas Köberle · Jan 17, 2013

Here is a simple way to mock it with Jasmine:

beforeEach(function () {
  var store = {};

  spyOn(localStorage, 'getItem').andCallFake(function (key) {
    return store[key];
  });
  spyOn(localStorage, 'setItem').andCallFake(function (key, value) {
    return store[key] = value + '';
  });
  spyOn(localStorage, 'clear').andCallFake(function () {
      store = {};
  });
});

If you want to mock the local storage in all your tests, declare the beforeEach() function shown above in the global scope of your tests (the usual place is a specHelper.js script).