我试图通过玩笑来测试异步 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 块在我的测试中执行?无法测试大量代码会很烦人(因为我所有的请求都以相同的方式工作)。
预先感谢您对此的帮助。