Is there a way to mock localStorage with Jest?
I have tried many answers from this question however, none seemed to work on typescript as I keep getting:
"ReferenceError: localStorage is not defined"
I also tried to make my own mock setup file:
export const localStorageMock = {
getItem: jest.fn().mockImplementation(() => ({
data: ""
})),
removeItem: jest.fn().mockImplementation(() => ({
data: ""
})),
};
And linking it like so:
jest.mock('localStorage', () => {
return jest.fn().mockImplementation(() => localStorageMock);
});
Is there a way to do it? I only need to use getItem and removeItem for the methods I wish to test.
2
Answers
You can mock local storage like this:
Then in your test file you can set the mockLocalStorage as the local storage you want to use like this:
This may not be the best way of doing this, but it’s a way that has worked for me in the past.
You can simply achieve this by defining a
localStorage
property onwindows
object.localStorageMock.ts :
Now, in your test file, import the above file
localStorageMock.ts
and use Jest’s function to mock thelocalStorage
: