Jest mock localStorage methods

前端 未结 4 934
猫巷女王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
    }
    
    0 讨论(0)
  • 2021-01-06 11:57

    If you want to test localStorage functions then I would like to suggest the jest-localstorage-mock npm package.

    After configuring this package in your setup test file as per documentation, then you could do this after.

    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
    });
    
    0 讨论(0)
  • 2021-01-06 12:05

    jest.spyOn(window.localStorage.__proto__, 'setItem'); works with nothing else at all needed, as noted here: https://github.com/facebook/jest/issues/6798#issuecomment-440988627

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题