How do I deal with localStorage in jest tests?

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

    You need to mock local storage with this snippets

    // localStorage.js

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

    And in the jest config:

    "setupFiles":["localStorage.js"]
    

    Feel free to ask anything .

提交回复
热议问题