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

How do I make API methods throw an exception

dentuzhik opened this issue · comments

Here's a checklist you can use to make sure your issue can be more easily resolved:

  • Check against the latest
  • Include a link to the example application source code

I am trying to write a test, which assumes that sometimes getItem or setItem throw, this can happen f.e. if you are browser LS is running out of space.

What I've tried:

  • localStorage.setItem.mockImplementation(() => { throw new Error('error') })
  • jest.spyOn(localStorage, 'setItem').mockImplementation(() => { throw new Error('error') })

Both examples work, however I cannot restore mocks to original behaviour defined in the library, I've tried:

  • jest.resetAllMocks or localStorage.setItem.mockReset for 1st example
  • jest.restoreAllMocks or localStorage.setItem.mockRestore for 2nd example

Am I missing something obvious or is it methods defined through defineProperty prevents me from doing this?

I would have thought the first approach with mockReset would have worked. 🤔

In a way it does, it just doesn't work properly after reset. I submitted failed test.

localStorage.setItem.mockImplementationOnce(() => { throw new Error('error'); }); should work, I think? mockImplementationOnce doesn't replace the default jest.fn(impl) (which is effectively an alias for jest.fn().mockImplementation(impl)), and automatically clears itself from the mock when triggered, thus preserving the default implementation for other tests.

☝️ seems to work for me, closing this out.