How to unit test localStorage using sinon

好久不见. 提交于 2019-12-06 01:57:39
Umair Sarfraz

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.

You can use babel-plugin-rewire to replace localStorage with mocked version in all your tests.

This is how I use it:

import {unauth, signOut, __RewireAPI__} from 'modules/auth/actions';

const rewrite = __RewireAPI__.__Rewire__;

const local = {}; // object where you store all values localStorage needs to return
const storage = {
  get(key) {
    return local[key];
  },
  set: sinon.spy(),
  remove: sinon.spy()
};

rewrite('storage', storage); // rewrite storage package with your mocked version

// in you test add values you want to get from localStorage
local.credentials = constants.CREDENTIALS;
local.authToken = constants.TOKEN;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!