unit-testing - 通过 jest mock 测试 catch block

标签 unit-testing redux jestjs

我正在尝试通过玩笑测试异步 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 块在我的测试中执行?无法测试大量代码会很烦人(因为我所有的请求都以相同的方式工作)。

在此先感谢您的帮助。

最佳答案

我不知道它是否仍然相关,但你可以这样做:

it('tests error with async/await', async () => {
  expect.assertions(1);
  try {
    await store.dispatch(userActions.loginUser('foo', 'bar'));
  } catch (e) {
    expect(e).toEqual({
      error: 'error',
    });
  }
});

这是一个关于错误处理的 documentation

关于unit-testing - 通过 jest mock 测试 catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42439532/

相关文章:

java - 接口(interface)模拟工作不正常

react-native - React Native中可能存在未处理的Promise Rejection网络错误

javascript - 从 API 结果覆盖索引数组

unit-testing - 模拟 Vuex getter 进行单元测试会产生意想不到的结果

javascript - Jest 模拟函数的内部变量并改变函数的行为?

angularjs - 如何使用 $setPristine 对 AngularJS Controller 进行单元测试

ruby-on-rails - 在 Rails 中,我如何测试在 Controller 中对模型实例所做的修改?

javascript - 函数未定义 store.getState()

unit-testing - 如何测试 ReactDOM.render 和另一个导入函数在 Jest 中被调用?

unit-testing - 不明白 Spock 中的交互是如何运作的