How to mock localStorage in JavaScript unit tests?

前端 未结 14 1634
南笙
南笙 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条回答
  •  悲&欢浪女
    2020-11-29 19:23

    Are there any libraries out there to mock localStorage?

    I just wrote one:

    (function () {
        var localStorage = {};
        localStorage.setItem = function (key, val) {
             this[key] = val + '';
        }
        localStorage.getItem = function (key) {
            return this[key];
        }
        Object.defineProperty(localStorage, 'length', {
            get: function () { return Object.keys(this).length - 2; }
        });
    
        // Your tests here
    
    })();
    

    My initial testing shows that localStorage refuses to be assignable in firefox

    Only in global context. With a wrapper function as above, it works just fine.

提交回复
热议问题