Can't mock localstorage method with jest.fn
See original GitHub issue🐛 Bug Report
It is impossible to mock a localStorage
method
To Reproduce
Using the following code:
it( 'setItem mock fn', () => {
const mockFn = jest.fn( localStorage.setItem );
localStorage.setItem = mockFn;
localStorage.setItem( 'foo', 'bar' );
expect( mockFn ).toHaveBeenCalledTimes( 1 );
} );
I have the following error: Expected mock function to have been called one time, but it was called zero times.
Expected behavior
No error should be thrown, since setItem
is called during the test.
Link to repl or repo (highly encouraged)
Run npx envinfo --preset jest
System:
OS: Linux 4.15 Pop!_OS 18.04 LTS
CPU: x64 Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz
Binaries:
Node: 10.9.0 - /usr/local/bin/node
npm: 6.2.0 - /usr/local/bin/npm
npmPackages:
jest: ^23.5.0 => 23.5.0
Comments
I suppose this is related to an error I saw earlier, making me think that localStorage
and sessionStorage
are proxies.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:3
- Comments:10 (2 by maintainers)
Top Results From Across the Web
How do I deal with localStorage in jest tests? - Stack Overflow
Currently (Jul '22) localStorage can not be mocked or spied on by jest as you usually would, and as outlined in the create-react-app...
Read more >Mocking browser APIs in Jest (localStorage, fetch and more!)
Sadly, mocking methods on a class instance (i.e. localStorage. getItem ) doesn't work with our jest. fn approach. But don't fret!
Read more >[Solved]-Jest mock localStorage methods-Reactjs
[Solved]-Jest mock localStorage methods-Reactjs ... This goes inline with what Andreas suggested in the answer, but i was able to mock it using...
Read more >Jest Mock Local Storage
Can't mock localstorage method with jest. Fabrizio Fortunato goes the extra mile to mock localStorage and . How to test LocalStorage with Jest?...
Read more >How to inject localStorage into jest tests - The Aurelia Discourse
I can't work out how to “initialize” this service when testing the services I am injecting ... const mockLocalService = { set:jest.fn(), get:jest.fn()...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Brilliant! For those with the error, simply use spy:
const spy = jest.spyOn(Storage.prototype, 'setItem');
For those wanting to mock localstorage and not simply spy on it, this worked for me: