Jest mock localStorage methods

前端 未结 4 933
猫巷女王i
猫巷女王i 2021-01-06 11:15

I would like to mock localStorage methods in jest for error simulation. I have localstorage getter and setter methods defined in utility.js. I would like to mock local

4条回答
  •  一整个雨季
    2021-01-06 12:09

    This goes inline with what Andreas suggested in the answer, but i was able to mock it using Storage interface. I did something like this,

    In jest,

    test('throw error', () => {
      Storage.prototype.setItem = jest.fn(() => {
        console.log(" called "); // <-- was called 
        throw new Error('ERROR');
      });
    
      utility.setItem('123', 'value');
    });
    

    Also this PR discussion was helpful.

提交回复
热议问题