How to mock localStorage in JavaScript unit tests?

前端 未结 14 1616
南笙
南笙 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条回答
  •  萌比男神i
    2020-11-29 19:12

    Unfortunately, the only way we can mock the localStorage object in a test scenario is to change the code we're testing. You have to wrap your code in an anonymous function (which you should be doing anyway) and use "dependency injection" to pass in a reference to the window object. Something like:

    (function (window) {
       // Your code
    }(window.mockWindow || window));
    

    Then, inside of your test, you can specify:

    window.mockWindow = { localStorage: { ... } };
    

提交回复
热议问题