How do I deal with localStorage in jest tests?

后端 未结 17 1757
长情又很酷
长情又很酷 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:56

    To do the same in the Typescript, do the following:

    Setup a file with the following contents:

    let localStorageMock = (function() {
      let store = new Map()
      return {
    
        getItem(key: string):string {
          return store.get(key);
        },
    
        setItem: function(key: string, value: string) {
          store.set(key, value);
        },
    
        clear: function() {
          store = new Map();
        },
    
        removeItem: function(key: string) {
            store.delete(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",

    Or you import this file in your test case where you want to mock the localstorage.

提交回复
热议问题