in my react + redux app I have an action that besides returning type and payload also changes localStorage like:
export const cancel = () => {
localStorage.removeItem("MyAppData");
return { type: types.USER_CANCEL};
};
my test looks like:
test("user cancels", () => {
const action = actions.cancel();
expect(action).toEqual({
type: types.USER_CANCEL
});
});
writing no test for local storage I get
● user cancels
ReferenceError: localStorage is not defined
33 |
34 | export const cancel = () => {
> 35 | localStorage.removeItem("MyAppData");
| ^
36 | return { type: types.USER_CANCEL};
37 | };
38 |
at Object.localStorage [as cancel] (src/actions/AllActions.js:35:3)
at Object.cancel (__test__/actions/AllActions.test.js:56:26)
Therefore I made a mock for local storage
const mockStorage = {};
const localStorage = {
setItem: (key, val) => Object.assign(mockStorage, { [key]: val }),
getItem: key => mockStorage[key],
removeItem: key => {delete mockStorage[key];console.log("Deleted: ", key);},
clear: () => mockStorage
};
export default localStorage;
either importing this mock or using localStorage API, I still get same error
I got confused in how should I test that when I call cancel()
also localStorge.removeItem
is also called or the key and value is removed?