【发布时间】:2017-07-15 08:07:01
【问题描述】:
我正在尝试通过 jest 测试异步 redux 操作的“catch”块,但是在模拟中抛出一个 catch 会导致整个测试失败。
我的操作如下:
export function loginUser(username, password) {
return async dispatch => {
dispatch({type: UPDATE_IN_PROGRESS});
try {
let response = await MyRequest.postAsync(
'/login', {username: username, password: password}
);
dispatch({
type: USER_AUTHENTICATED,
username: response.username,
token: response.token,
role: response.role,
id: response.id
});
} catch (error) {
dispatch({type: USER_SIGNED_OUT});
throw error;
} finally {
dispatch({type: UPDATE_COMPLETE});
}
};
}
测试试图模拟“MyRequest.postAsync”以引发错误并因此触发 catch 块,但测试只是退出并显示“失败”消息
it('calls expected actions when failed log in', async() => {
MyRequest.postAsync = jest.fn(() => {
throw 'error';
});
let expectedActions = [
{type: UPDATE_IN_PROGRESS},
{type: USER_SIGNED_OUT},
{type: UPDATE_COMPLETE}
];
await store.dispatch(userActions.loginUser('foo', 'bar'));
expect(store.getActions()).toEqual(expectedActions);
});
有没有办法通过一个笑话模拟函数(或任何其他方式)触发 catch 块在我的测试中执行?无法测试大量代码会很烦人(因为我所有的请求都以相同的方式工作)。
在此先感谢您的帮助。
【问题讨论】:
-
给你用
jest.mock模拟MyRequest,否则不行 -
对不起@AndreasKöberle 你能稍微详细说明一下吗?使用 jest.fn() 似乎可以很好地模拟导入模块上的函数,这是导致问题的
throw 'error' -
可能是
catch块中的throw
标签: unit-testing redux jestjs