Related issues: #638 and #848.
When running my jest tests with redux-persist v5 (5.10.0 to be precise), I get the following console.error message:
PASS src/__tests__/reducers-test.js
โ Console
console.error node_modules/redux-persist/lib/storage/getStorage.js:40
redux-persist failed to create sync storage. falling back to memory storage.
What is the proper method to remove this message from my output ?
Note that my code imports storage as follow in my root reducer file:
import localStorage from "redux-persist/lib/storage";
+1, is anyone by chance working on that ? I'm using Jest for tests
+1 I'm having the same error.
This is not the proper solution, but a workaround would be to mock localStorage.
Thanks! The solution at the link didn't work for me, but this one from StackOverflow did:
in src/setupTests.js file add
class LocalStorageMock {
constructor() {
this.store = {};
}
clear() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value.toString();
}
removeItem(key) {
delete this.store[key];
}
};
global.localStorage = new LocalStorageMock;
I'm using the create-react-app utility which has a script that causes my src/setupTests.js file to run automatically when testing starts. If you have a different setup you might need to put this code somewhere else. Just make sure it runs before your tests start.
Thanks @seeker105 - stubbing it worked!
for those of you who have implemented something apart from localStorage, don't forget to change your class accordingly. I wasted 10 minutes on trying to figure why the mock wasn't working!
Example below is for those using sessionStorage(based on @seeker105 's comment above):
class SessionStorageMock {
constructor() {
this.store = {};
}
clear() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value.toString();
}
removeItem(key) {
delete this.store[key];
}
};
global.sessionStorage = new SessionStorageMock;
I wanna +1 and bump this, I know the getStorage function already checks if NODE_ENV !== production, so it could also check if the env is test too.
It's easy to open a PR for this change, I just don't know if it is something you're interested in.
@seeker105 works great!
Most helpful comment
Thanks! The solution at the link didn't work for me, but this one from StackOverflow did:
in
src/setupTests.jsfile addI'm using the create-react-app utility which has a script that causes my
src/setupTests.jsfile to run automatically when testing starts. If you have a different setup you might need to put this code somewhere else. Just make sure it runs before your tests start.