【发布时间】:2019-02-14 08:07:10
【问题描述】:
在我的 react + redux 应用程序中,我有一个动作,除了返回类型和有效负载之外,还会更改 localStorage,例如:
export const cancel = () => {
localStorage.removeItem("MyAppData");
return { type: types.USER_CANCEL};
};
我的测试看起来像:
test("user cancels", () => {
const action = actions.cancel();
expect(action).toEqual({
type: types.USER_CANCEL
});
});
我没有为本地存储编写测试
● 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)
因此我为本地存储做了一个模拟
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;
无论是导入这个模拟还是使用 localStorage API,我仍然得到同样的错误
我对如何测试当我调用cancel() 时也调用localStorge.removeItem 或删除键和值感到困惑?
【问题讨论】: