在失败情况下测试异步redux动作

时间:2020-05-25 15:03:36

标签: reactjs react-redux jestjs redux-async-actions

我已经测试过成功案例。但是我对失败案例感到困惑。

这是我的行动

ALLOW-FROM

服务文件

const register = (user) => async (dispatch) => {
  try {
    dispatch(registerRequest());
    const response = await userService.register(user);

    dispatch(registerSuccess(response.data));
    history.push("/");
  } catch (err) {

    dispatch(registerFailure());
    dispatch(errorActions.setErrors(err));
  }
};

我的测试文件如下。我也有一个我称为api call的用户服务。我会在行动中使用该服务

const register = async (user) => {
  const response = await axios.post(`${API_AUTH}/register`, user);
  return response;
};

我的测试结果就像

    describe("async actions", () => {
      const user = {
        name: "ogulcan133",
        password: "133131",
        email: "kara@gmail.com",
      };
      let response;
      beforeEach(() => {
        moxios.install();
      });

      afterEach(() => {
        moxios.uninstall();
      });


      it("creates registerRequest and registerFailure when user register has been done with fail", () => {
        response = new Error("Request failed with status code 500");
        const store = makeMockStore();

        const expectedActions = [
          authActions.registerRequest(),
          authActions.registerFailure(),
          errorActions.setErrors(response),
        ];

        moxios.wait(() => {
          const request = moxios.requests.mostRecent();
          request.respondWith({
            status: 500,
            response: response,
          });
        });
        return store.dispatch(authActions.register(user)).then(() => {
          // return of async actions

          expect(store.getActions()).toEqual(expectedActions);
        });
      });
    });

哪些行代码必须更改?或在该问题上我应该怎么做。感谢您的帮助

0 个答案:

没有答案