clarkbw / jest-localstorage-mock

A module to mock window.localStorage and window.sessionStorage in Jest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

reset jest mock functions

Aligertor opened this issue · comments

I cannot run multiple tests without beeing sure that the evaluateing the jest.fn()´s are actually called only from the current test.

for example test like this will pass when run together but the second test will fail when run allone

test('should save to localStorage', () => {
  const KEY = 'foo', VALUE = 'bar';
  dispatch(action.update(KEY, VALUE));
  expect(localStorage.setItem).toHaveBeenCalledTimes(1);
});

test('should save to localStorage again', () => {
  const KEY = 'fooo', VALUE = 'barr';
  dispatch(action.update(KEY, VALUE));
  expect(localStorage.setItem).toHaveBeenCalledTimes(2);
});

there should be a way to reinitalize the mock functions in a beforeEach block so i can be sure that their calls are only from the current test and or related beforeEach blocks.

You should be able to use jest.resetAllMocks() and / or mockFn.mockReset()

Like so:

beforeEach(() => {
  // reset all mocks, which could impact your other mocks
  jest.resetAllMocks();
  // or individually
  localStorage.setItem.mockClear();
  // note that values stored will also be available in other tests you may also want
  localStorage.clear();
});

test('should save to localStorage', () => {
  const KEY = 'foo', VALUE = 'bar';
  dispatch(action.update(KEY, VALUE));
  expect(localStorage.setItem).toHaveBeenCalledTimes(1);
  // or after each use
  localStorage.setItem.mockClear();
  localStorage.clear();
});

test('should save to localStorage again', () => {
  const KEY = 'fooo', VALUE = 'barr';
  dispatch(action.update(KEY, VALUE));
  expect(localStorage.setItem).toHaveBeenCalledTimes(2);
});

If this answers your question, could you create a pull request to add this to the README? thx

I think what you want here is mockClear() rather than mockReset(). The latter will completely wipe the mock implementation.

Thanks @iprignano I'll fix up the comment to use clear instead.