开玩笑模拟本地存储方法

问题描述 投票:0回答:5

我想在玩笑中模拟 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
mock永远不会被调用。我也尝试过做

window.localStorage.setItem = jest.genMockFunction(()=>{console.log(" Mock Called")});
global.localStorage.setItem = jest.fn(()=>{console.log(" Mock Called")});
javascript reactjs local-storage jestjs
5个回答
24
投票

jest.spyOn(window.localStorage.__proto__, 'setItem');
无需任何其他操作即可使用,如下所示:https://github.com/facebook/jest/issues/6798#issuecomment-440988627


6
投票

这与 Andreas 在答案中的建议一致,但我能够使用 Storage 接口来模拟它。我做了这样的事情,

开玩笑地说,

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

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

这个PR讨论也很有帮助。


3
投票

如果你想测试 localStorage 功能,那么我建议使用 jest-localstorage-mock 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
});

1
投票

要访问被测模块全局范围内的内容,您需要使用

global
命名空间。因此,要访问
localStorage
,请使用
global.localStorage
:

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

0
投票

这里是 TS 版本 https://github.com/facebook/jest/issues/6798#issuecomment-440988627

import { afterAll, beforeAll } from '@jest/globals';

const mockWindowProperty = <P extends keyof Window>(property: P, value: Partial<Window[P]>) => {
  const { [property]: originalProperty } = window;
  delete window[property];
  beforeAll(() => {
    Object.defineProperty(window, property, {
      configurable: true,
      writable: true,
      value,
    });
  });
  afterAll(() => {
    window[property] = originalProperty;
  });
};

export default mockWindowProperty;
© www.soinside.com 2019 - 2024. All rights reserved.