嘲笑本地存储

时间:2019-03-18 19:02:12

标签: javascript jestjs

我正在尝试模拟本地存储,但是不断出现错误。

[1110100, 1100101, 1110011, 1110100]
Matcher error: received value must be a mock or spy function

我什至尝试过

const sessionStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
};

global.sessionStorage = sessionStorageMock;

test('expect', () => {
  mySessionSetFunction();
  expect(sessionStorage.setItem).toHaveBeenCalled();
});

但是它永远不会被调用。

1 个答案:

答案 0 :(得分:0)

这是一个解决方案:

function mySessionSetFunction() {
  sessionStorage.setItem('name', 'jest');
}

export { mySessionSetFunction };

单元测试:

/**
 * @jest-environment jsdom
 */
import { mySessionSetFunction } from './';

const sessionStorageBackup = (global as any).sessionStorage;

delete (global as any).sessionStorage;
(global as any).sessionStorage = {
  setItem: jest.fn()
};

describe('test suites', () => {
  afterAll(() => {
    (global as any).sessionStorage = sessionStorageBackup;
  });
  it('t1', () => {
    mySessionSetFunction();
    expect((global as any).sessionStorage.setItem).toBeCalledWith('name', 'jest');
    expect(jest.isMockFunction((global as any).sessionStorage.setItem)).toBeTruthy();
  });
});

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55228389