How to mock localStorage in JavaScript unit tests?

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

    The current solutions will not work in Firefox. This is because localStorage is defined by the html spec as being not modifiable. You can however get around this by accessing localStorage's prototype directly.

    The cross browser solution is to mock the objects on Storage.prototype e.g.

    instead of spyOn(localStorage, 'setItem') use

    spyOn(Storage.prototype, 'setItem')
    spyOn(Storage.prototype, 'getItem')
    

    taken from bzbarsky and teogeos's replies here https://github.com/jasmine/jasmine/issues/299

提交回复
热议问题