How to mock localStorage in JavaScript unit tests?

前端 未结 14 1622
南笙
南笙 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:30

    This is how I like to do it. Keeps it simple.

      let localStoreMock: any = {};
    
      beforeEach(() => {
    
        angular.mock.module('yourApp');
    
        angular.mock.module(function ($provide: any) {
    
          $provide.service('localStorageService', function () {
            this.get = (key: any) => localStoreMock[key];
            this.set = (key: any, value: any) => localStoreMock[key] = value;
          });
    
        });
      });
    

提交回复
热议问题