0

I'm trying to mock local storage but keep getting an error.

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();
});

I even tried.

  const spy = jest.spyOn(sessionStorage, 'setItem');
  expect(spy).toHaveBeenCalled();

but it never gets called.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
me-me
  • 5,139
  • 13
  • 50
  • 91
  • Look on https://stackoverflow.com/questions/32911630/how-do-i-deal-with-localstorage-in-jest-tests – begin29 Mar 18 '19 at 19:05
  • Yes saw that but it doesn't work. expect(localStorage.getItem).toBeCalledWith('token') – me-me Mar 18 '19 at 19:11
  • will `mySessionSetFunction()` creates `token` key within local storage? – begin29 Mar 18 '19 at 19:27
  • mySessionSetFunction() is just running through an object of keys and setting sessionStorage.setItem(key, value); – me-me Mar 18 '19 at 19:31
  • This worked for me. jest.spyOn(Storage.prototype, 'setItem'); Thanks for the help Vadym Motsukh – me-me Mar 18 '19 at 19:47

1 Answers1

0

Here is a solution:

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

export { mySessionSetFunction };

Unit test:

/**
 * @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();
  });
});

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55228389

Lin Du
  • 88,126
  • 95
  • 281
  • 483