I keep getting "localStorage is not defined" in Jest tests which makes sense but what are my options? Hitting brick walls.
Great solution from @chiedo
However, we use ES2015 syntax and I felt it was a little cleaner to write it this way.
class LocalStorageMock {
constructor() {
this.store = {};
}
clear() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = String(value);
}
removeItem(key) {
delete this.store[key];
}
};
global.localStorage = new LocalStorageMock;
-
10Should probably do
value + ''
in the setter to handle null and undefined values correctly – Andrew M. Sep 11 '17 at 15:42 -
I think that latest jest was just using that
|| null
that's why my test was failing, because in my test I was usingnot.toBeDefined()
. @Chiedo solution make it work again – jcubic Sep 7 '18 at 16:56 -
I think this is technically a stub :) see here for the mocked version: stackoverflow.com/questions/32911630/… – TigerBear Jan 17 '19 at 19:48
-
3Update 2021: For people using Jest@24 and above, localStorage is mocked automatically. – Niket Pathak Feb 24 at 21:59
-
1hi @NiketPathak, do you have a source for this? I couldn't find anything about it in the release notes for version 24 or the documentation. – AvantiC Mar 4 at 13:59
Figured it out with help from this: https://groups.google.com/forum/#!topic/jestjs/9EPhuNWVYTg
Setup a file with the following contents:
var localStorageMock = (function() {
var store = {};
return {
getItem: function(key) {
return store[key];
},
setItem: function(key, value) {
store[key] = value.toString();
},
clear: function() {
store = {};
},
removeItem: function(key) {
delete store[key];
}
};
})();
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
Then you add the following line to your package.json under your Jest configs
"setupTestFrameworkScriptFile":"PATH_TO_YOUR_FILE",
-
6Apparently with one of the updates the name of this parameter changed and now it is called "setupTestFrameworkScriptFile" – Grzegorz Pawlik Dec 9 '16 at 12:08
-
2
"setupFiles": [...]
works as well. With the array option, allows separating mocks into separate files. E.g.:"setupFiles": ["<rootDir>/__mocks__/localStorageMock.js"]
– Stiggler Mar 23 '17 at 21:07 -
4The return value of
getItem
differs slightly to what would be returned by a browser if the no data is set against a specific key. callinggetItem("foo")
when its not set will for example returnnull
in a browser, butundefined
by this mock - this was causing one of my tests to fail. Simple solution for me was to returnstore[key] || null
in thegetItem
function – Ben Broadley Mar 30 '17 at 19:39 -
1this doesn't work if you do something like
localStorage['test'] = '123'; localStorage.getItem('test')
– rob Oct 25 '17 at 20:58 -
3I am getting the following error - jest.fn() value must be a mock function or spy. Any ideas? – Paul Fitzgerald Dec 10 '18 at 16:53
If using create-react-app, there is a simpler and straightforward solution explained in the documentation.
Create src/setupTests.js
and put this in it :
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
Tom Mertz contribution in a comment below :
You can then test that your localStorageMock's functions are used by doing something like
expect(localStorage.getItem).toBeCalledWith('token')
// or
expect(localStorage.getItem.mock.calls.length).toBe(1)
inside of your tests if you wanted to make sure it was called. Check out https://facebook.github.io/jest/docs/en/mock-functions.html
-
Hi c4k! Could you please give an example how you would use that in your tests? – Dimo Dec 27 '17 at 10:05
-
What do you mean ? You don't have to initialize anything in your tests, it just mocks automatically the
localStorage
you use in your code. (if you usecreate-react-app
and all the automatic scripts it provides naturally) – c4k Dec 28 '17 at 10:58 -
You can then test that your localStorageMock's functions are used by doing something like
expect(localStorage.getItem).toBeCalledWith('token')
orexpect(localStorage.getItem.mock.calls.length).toBe(1)
inside of your tests if you wanted to make sure it was called. Check out facebook.github.io/jest/docs/en/mock-functions.html – Tom Mertz Jun 6 '18 at 17:35 -
16for this I am getting an error - jest.fn() value must be a mock function or spy. Any ideas? – Paul Fitzgerald Dec 10 '18 at 16:53
-
3Won't this cause problems if you have multiple tests that use
localStorage
? Wouldn't you want to reset the spies after each test to prevent "spillover" into other tests? – Brandon Sturgeon Jan 29 '19 at 17:16
Currently (Oct '19) localStorage can not be mocked or spied on by jest as you usually would, and as outlined in the create-react-app docs. This is due to changes made in jsdom. You can read about it in the jest and jsdom issue trackers.
As a workaround, you can spy on the prototype instead:
// does not work:
jest.spyOn(localStorage, "setItem");
localStorage.setItem = jest.fn();
// works:
jest.spyOn(window.localStorage.__proto__, 'setItem');
window.localStorage.__proto__.setItem = jest.fn();
// assertions as usual:
expect(localStorage.setItem).toHaveBeenCalled();
-
Actually it works for me just with the spyOn, no need to override setItem function
jest.spyOn(window.localStorage.__proto__, 'setItem');
– Yohan Dahmani Mar 19 '20 at 10:26 -
-
-
1Ah yes. I was saying you can use either the first line, or the second line. They are alternatives that do the same thing. Whatever is your personal preference :) Sorry about the confusion. – Bastian Stein Mar 24 '20 at 10:15
-
2FWIW, eslint now says that obj.__proto__ is deprecated and its best to use Object.getPrototypeOf(obj) instead. That also seems to work here. – Ken Pronovici Jun 26 '20 at 0:36
A better alternative which handles undefined
values (it doesn't have toString()
) and returns null
if value doesn't exist. Tested this with react
v15, redux
and redux-auth-wrapper
class LocalStorageMock {
constructor() {
this.store = {}
}
clear() {
this.store = {}
}
getItem(key) {
return this.store[key] || null
}
setItem(key, value) {
this.store[key] = value
}
removeItem(key) {
delete this.store[key]
}
}
global.localStorage = new LocalStorageMock
-
Thanks to Alexis Tyler for the idea to add
removeItem
: developer.mozilla.org/en-US/docs/Web/API/Storage/removeItem – Dmitriy May 25 '17 at 15:49 -
Believe null and undefined need to result in "null" and "undefined" (literal strings) – Andrew M. Sep 11 '17 at 15:44
or you just take a mock package like this:
https://www.npmjs.com/package/jest-localstorage-mock
it handles not only the storage functionality but also allows you test if the store was actually called.
Unfortunately, the solutions that I've found here didn't work for me.
So I was looking at Jest GitHub issues and found this thread
The most upvoted solutions were these ones:
const spy = jest.spyOn(Storage.prototype, 'setItem');
// or
Storage.prototype.getItem = jest.fn(() => 'bla');
-
My tests don't have
window
orStorage
defined either. Maybe it's the older version of Jest I'm using. – Antrikshy May 20 '20 at 23:24 -
If you are looking for a mock and not a stub, here is the solution I use:
export const localStorageMock = {
getItem: jest.fn().mockImplementation(key => localStorageItems[key]),
setItem: jest.fn().mockImplementation((key, value) => {
localStorageItems[key] = value;
}),
clear: jest.fn().mockImplementation(() => {
localStorageItems = {};
}),
removeItem: jest.fn().mockImplementation((key) => {
localStorageItems[key] = undefined;
}),
};
export let localStorageItems = {}; // eslint-disable-line import/no-mutable-exports
I export the storage items for easy initialization. I.E. I can easily set it to an object
In the newer versions of Jest + JSDom it is not possible to set this, but the localstorage is already available and you can spy on it it like so:
const setItemSpy = jest.spyOn(Object.getPrototypeOf(window.localStorage), 'setItem');
I found this solution from github
var localStorageMock = (function() {
var store = {};
return {
getItem: function(key) {
return store[key] || null;
},
setItem: function(key, value) {
store[key] = value.toString();
},
clear: function() {
store = {};
}
};
})();
Object.defineProperty(window, 'localStorage', {
value: localStorageMock
});
You can insert this code in your setupTests and it should work fine.
I tested it in a project with typesctipt.
-
for me Object.defineProperty made the trick. Direct object assignment did not work. Thanks! – Vicens Fayos Dec 8 '19 at 13:33
-
-
you should use mock data instead of services for testing. In unit tests you should test a single functionality. – Carlos Huamani Sep 4 '20 at 23:52
You need to mock local storage with this snippets
// localStorage.js
var localStorageMock = (function() {
var store = {};
return {
getItem: function(key) {
return store[key] || null;
},
setItem: function(key, value) {
store[key] = value.toString();
},
clear: function() {
store = {};
}
};
})();
Object.defineProperty(window, 'localStorage', {
value: localStorageMock
});
And in the jest config:
"setupFiles":["localStorage.js"]
Feel free to ask anything .
As @ck4 suggested documentation has clear explanation for using localStorage
in jest. However the mock functions were failing to execute any of the localStorage
methods.
Below is the detailed example of my react component which make uses of abstract methods for writing and reading data,
//file: storage.js
const key = 'ABC';
export function readFromStore (){
return JSON.parse(localStorage.getItem(key));
}
export function saveToStore (value) {
localStorage.setItem(key, JSON.stringify(value));
}
export default { readFromStore, saveToStore };
Error:
TypeError: _setupLocalStorage2.default.setItem is not a function
Fix:
Add below mock function for jest (path: .jest/mocks/setUpStore.js
)
let mockStorage = {};
module.exports = window.localStorage = {
setItem: (key, val) => Object.assign(mockStorage, {[key]: val}),
getItem: (key) => mockStorage[key],
clear: () => mockStorage = {}
};
Snippet is referenced from here
You can use this approach, to avoid mocking.
Storage.prototype.getItem = jest.fn(() => expectedPayload);
-
how to setup some service to load the data from localStorage ? Here is my question stackoverflow.com/questions/63716411/… – Darmawan Zulkifli Sep 3 '20 at 4:54
Riffed off some other answers here to solve it for a project with Typescript. I created a LocalStorageMock like this:
export class LocalStorageMock {
private store = {}
clear() {
this.store = {}
}
getItem(key: string) {
return this.store[key] || null
}
setItem(key: string, value: string) {
this.store[key] = value
}
removeItem(key: string) {
delete this.store[key]
}
}
Then I created a LocalStorageWrapper class that I use for all access to local storage in the app instead of directly accessing the global local storage variable. Made it easy to set the mock in the wrapper for tests.
describe('getToken', () => {
const Auth = new AuthService();
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ik1yIEpvc2VwaCIsImlkIjoiNWQwYjk1Mzg2NTVhOTQ0ZjA0NjE5ZTA5IiwiZW1haWwiOiJ0cmV2X2pvc0Bob3RtYWlsLmNvbSIsInByb2ZpbGVVc2VybmFtZSI6Ii9tcmpvc2VwaCIsInByb2ZpbGVJbWFnZSI6Ii9Eb3Nlbi10LUdpci1sb29rLWN1dGUtbnVrZWNhdDMxNnMtMzExNzAwNDYtMTI4MC04MDAuanBnIiwiaWF0IjoxNTYyMzE4NDA0LCJleHAiOjE1OTM4NzYwMDR9.YwU15SqHMh1nO51eSa0YsOK-YLlaCx6ijceOKhZfQZc';
beforeEach(() => {
global.localStorage = jest.fn().mockImplementation(() => {
return {
getItem: jest.fn().mockReturnValue(token)
}
});
});
it('should get the token from localStorage', () => {
const result = Auth.getToken();
expect(result).toEqual(token);
});
});
Create a mock and add it to the global
objectt
To do the same in the Typescript, do the following:
Setup a file with the following contents:
let localStorageMock = (function() {
let store = new Map()
return {
getItem(key: string):string {
return store.get(key);
},
setItem: function(key: string, value: string) {
store.set(key, value);
},
clear: function() {
store = new Map();
},
removeItem: function(key: string) {
store.delete(key)
}
};
})();
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
Then you add the following line to your package.json under your Jest configs
"setupTestFrameworkScriptFile":"PATH_TO_YOUR_FILE",
Or you import this file in your test case where you want to mock the localstorage.
I thought I would add another solution that worked very neatly for me in TypeScript w/ React:
I created a mockLocalStorage.ts
export const mockLocalStorage = () => {
const setItemMock = jest.fn();
const getItemMock = jest.fn();
beforeEach(() => {
Storage.prototype.setItem = setItemMock;
Storage.prototype.getItem = getItemMock;
});
afterEach(() => {
setItemMock.mockRestore();
getItemMock.mockRestore();
});
return { setItemMock, getItemMock };
};
My component:
export const Component = () => {
const foo = localStorage.getItem('foo')
return <h1>{foo}</h1>
}
then in my tests I use it like so:
import React from 'react';
import { mockLocalStorage } from '../../test-utils';
import { Component } from './Component';
const { getItemMock } = mockLocalStorage();
it('fetches something from localStorage', () => {
getItemMock.mockReturnValue('bar');
render(<Component />);
expect(getItemMock).toHaveBeenCalled();
expect(getByText(/bar/i)).toBeInTheDocument()
});
The following solution is compatible for testing with stricter TypeScript, ESLint, TSLint, and Prettier config: { "proseWrap": "always", "semi": false, "singleQuote": true, "trailingComma": "es5" }
:
class LocalStorageMock {
public store: {
[key: string]: string
}
constructor() {
this.store = {}
}
public clear() {
this.store = {}
}
public getItem(key: string) {
return this.store[key] || undefined
}
public setItem(key: string, value: string) {
this.store[key] = value.toString()
}
public removeItem(key: string) {
delete this.store[key]
}
}
/* tslint:disable-next-line:no-any */
;(global as any).localStorage = new LocalStorageMock()
HT/ https://stackoverflow.com/a/51583401/101290 for how to update global.localStorage
This worked for me,
delete global.localStorage;
global.localStorage = {
getItem: () =>
}