开玩笑模拟localStorage方法

时间:2018-10-18 21:48:59

标签: javascript reactjs local-storage jestjs

我想开玩笑地模拟localStorage方法以进行错误模拟。我在Utility.js中定义了localstorage getter和setter方法。我想模拟localStorage.setItem在调用utility.setItem时引发错误。

//file: utility.js
export default {
  getItem(key) {
    return localStorage.getItem(key);
  },
  setItem(key, value) {
    localStorage.setItem(key, value);
  }
};

开玩笑

test('throw error', () => {
  localStorage.setItem = jest.fn(() => {
    console.log(" called ");
    throw new Error('ERROR');
  });

  utility.setItem('123', 'value');
});

但是localStorage.setItem模拟永远不会被调用。我也尝试过

window.localStorage.setItem = jest.genMockFunction(()=>{console.log(" Mock Called")});
global.localStorage.setItem = jest.fn(()=>{console.log(" Mock Called")});

4 个答案:

答案 0 :(得分:2)

[['a', 'b17', 'c', 'dz', 'e', 'ff', 'e3'], ['e66', 'a', 'b17', 'c', 'dz', 'e', 'ff'], ['e3', 'e66', 'a', 'b17', 'c', 'dz', 'e'], ['ff', 'e3', 'e66', 'a', 'b17', 'c', 'dz'], ['e', 'ff', 'e3', 'e66', 'a', 'b17', 'c']] 根本不需要其他任何东西,如此处所述:https://github.com/facebook/jest/issues/6798#issuecomment-440988627

答案 1 :(得分:1)

如果您想测试localStorage函数,那么我想建议一个this好的npm软件包。

按照文档在安装测试文件中配置此程序包后,您可以在此之后执行此操作。

test('should save to localStorage', () => {
  const KEY = 'foo',
    VALUE = 'bar';
  dispatch(action.update(KEY, VALUE));
  expect(localStorage.setItem).toHaveBeenLastCalledWith(KEY, VALUE);
  expect(localStorage.__STORE__[KEY]).toBe(VALUE);
  expect(Object.keys(localStorage.__STORE__).length).toBe(1);
});


test('should have cleared the sessionStorage', () => {
  dispatch(action.reset());
  expect(sessionStorage.clear).toHaveBeenCalledTimes(1);
  expect(sessionStorage.__STORE__).toEqual({}); // check store values
  expect(sessionStorage.length).toBe(0); // or check length
});

答案 2 :(得分:1)

要访问被测模块的全局范围内的内容,您需要使用global名称空间。因此,使用localStorage来访问global.localStorage

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

答案 3 :(得分:0)

这与Andreas在答案中建议的内容一致,但我能够使用Storage界面对其进行模拟。我做了这样的事情,

开玩笑

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

  utility.setItem('123', 'value');
});

这个PR的讨论也很有帮助。