How to mock localStorage in JavaScript unit tests?

前端 未结 14 1617
南笙
南笙 2020-11-29 18:46

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 gr

14条回答
  •  萌比男神i
    2020-11-29 19:21

    This is what I do...

    var mock = (function() {
      var store = {};
      return {
        getItem: function(key) {
          return store[key];
        },
        setItem: function(key, value) {
          store[key] = value.toString();
        },
        clear: function() {
          store = {};
        }
      };
    })();
    
    Object.defineProperty(window, 'localStorage', { 
      value: mock,
    });
    

提交回复
热议问题