Jest mock localStorage methods

前端 未结 4 935
猫巷女王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 11:50

    To access something that is in the global scope of your module under test, you need to use the global namespace. So to access localStorage use global.localStorage:

    global.storage = {
      store:{},
      getItem: (key)=>this.store[key],
      setItem: (key, value)=> this.store[key] = value
    }
    

提交回复
热议问题