How do I deal with localStorage in jest tests?

后端 未结 17 1790
长情又很酷
长情又很酷 2020-11-28 02:01

I keep getting \"localStorage is not defined\" in Jest tests which makes sense but what are my options? Hitting brick walls.

17条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 02:54

    Figured it out with help from this: https://groups.google.com/forum/#!topic/jestjs/9EPhuNWVYTg

    Setup a file with the following contents:

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

    Then you add the following line to your package.json under your Jest configs

    "setupTestFrameworkScriptFile":"PATH_TO_YOUR_FILE",

提交回复
热议问题