How to unit test localStorage using sinon

Umair Sarfraz picture Umair Sarfraz · Aug 15, 2016 · Viewed 7.8k times · Source

I am trying to test localStorage using sinon. Basically I am very new to unit testing so this might be very basic.

Update

I managed to come up with this but now its giving me a new error Should wrap property of object

Test

describe('Initial State', () => {
    it('should set the initial state for the component', () => {
const props = {
        currentUser: {}
      };
      sinon.stub(window.localStorage, 'setItem');
      window.localStorage.setItem('none', 'nothing');
    });
  });

Answer

Umair Sarfraz picture Umair Sarfraz · Aug 16, 2016

I managed to resolve it. Thanks to @anoop because his answer was of help but I had to manage it with a major workaround. I am using jsdom and it currently DOES NOT support localStorage. I added a fake in my jsdom configuration.

if (!global.window.localStorage) {
  global.window.localStorage = {
    getItem() { return '{}'; },
    setItem() {}
  };
}

And asserted it with:

it('should fetch from local storage', () => {
      const props = {
        currentUser: 'UMAIR',
        user: {
          is_key: false
        }
      };

      const spy = sinon.spy(global.window.localStorage, "setItem");
      spy(props);
      expect(spy.calledWith( {
        currentUser: 'UMAIR',
        user: {
          is_key: false
        }
      }));
      spy.restore();

      const stub = sinon.stub(global.window.localStorage, 'getItem');
      stub(props);
      expect(stub.calledWith(Object.keys(props)));
// stub.restore();
    });

Also see: How to mock localStorage in JavaScript unit tests?

https://github.com/gor181/webpack-react-babel-mocha-boilerplate/tree/master/test/utils

I also found an internal issue in Sinon a week ago related to this but that has been resolved.

See: https://github.com/sinonjs/sinon/issues/1129

Hope this helps someone.