测试redux saga回调函数

时间:2020-06-18 04:40:45

标签: redux jestjs redux-saga redux-saga-test-plan

在saga函数中,成功后,我正在执行回调。我试图在测试中涵盖这一点,但并未涵盖。谁能建议一些方法来覆盖这些领域。

export function* submitSavedDataWorker(action) {
      try {
        const response = yield call(suggestFunction, action.payload);
        const { data } = action.payload;
        yield put({
          type: actionTypes.suggestType,
          payload: response.data,
          prevData: data,
        });
        if (action.successFn) {
          action.successFn(response.data);
        }
      } catch (error) {
        const { charityData } = action.payload;
        yield put({
          type: actionTypes.saveFailType,
          payload: error,
          prevData: data,
        });
      }
    }

我编写了如下的测试用例:

describe('submitSavedDataWorker success', ()=> {
      const it = sagaHelper(
        submitSavedDataWorker({ payload: { data: 1234 }, successFn: ()=> { return 0 } })
      );
      it("should get error as result", (result) => {
        expect(result).toEqual(
          call(suggestFunction, { data: 1234 })
        );
        return {data: true};
      });
      it("should get success as result", (result) => {
        expect(result).toEqual(
          put({
            type: actionTypes.suggestType,
            payload: true,
            prevData: 1234,
          })
        );
      });
    });

1 个答案:

答案 0 :(得分:0)

sagaHelper仅在调用it时一次将传奇向前推进一个效果-因此,生成器在产生put效果后停止执行。为了使传奇故事完成(从而执行未覆盖的行),it需要再调用一次。您还可以检查结果是否为undefined,以确保传奇已完成,例如:

      it("should complete", (result) => {
        expect(result).toBeUndefined();
      });

有了这个补充,下面是完整的测试:

describe('submitSavedDataWorker success', ()=> {
      const it = sagaHelper(
        submitSavedDataWorker({ payload: { data: 1234 }, successFn: ()=> { return 0 } })
      );
      it("should get error as result", (result) => {
        expect(result).toEqual(
          call(suggestFunction, { data: 1234 })
        );
        return {data: true};
      });
      it("should get success as result", (result) => {
        expect(result).toEqual(
          put({
            type: actionTypes.suggestType,
            payload: true,
            prevData: 1234,
          })
        );
      });
      /* New code is here */
      it("should complete", (result) => {
        expect(result).toBeUndefined();
      });
    });