How to mock localStorage in JavaScript unit tests?

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

    Here is an exemple using sinon spy and mock:

    // window.localStorage.setItem
    var spy = sinon.spy(window.localStorage, "setItem");
    
    // You can use this in your assertions
    spy.calledWith(aKey, aValue)
    
    // Reset localStorage.setItem method    
    spy.reset();
    
    
    
    // window.localStorage.getItem
    var stub = sinon.stub(window.localStorage, "getItem");
    stub.returns(aValue);
    
    // You can use this in your assertions
    stub.calledWith(aKey)
    
    // Reset localStorage.getItem method
    stub.reset();
    

提交回复
热议问题