Testing catch block via jest mock

And*_*Law 6 unit-testing jestjs redux

I'm trying to test the 'catch' block of an async redux action via jest, but throwing a catch in the mock causes the test as a whole to fail.

My action is as follows:

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});
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

The test is trying to mock up 'MyRequest.postAsync' to throw an error and thus trigger the catch block, but the test just bails with a 'Failed' message

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);
});
Run Code Online (Sandbox Code Playgroud)

Is there a way to trigger the catch block to execute in my test via a jest mock function (or any other way for that matter)? Would be annoying to not be able to test a large chunk of code (as all my requests work in the same way).

Thanks in advance for help with this.

Yev*_*huk 8

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

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',
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

这是有关错误处理的文档


小智 2

我遇到过同样的问题。对我来说以下有效。结束等待try/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}
  ];
  try {
     await store.dispatch(userActions.loginUser('foo', 'bar'));
  } catch(e) {
     expect(store.getActions()).toEqual(expectedActions);
  }

});
Run Code Online (Sandbox Code Playgroud)