Search code examples
reduxjestjsredux-sagaredux-saga-test-plan

testing redux saga callback function


In the saga function, after success, I am doing a callback. I tried to cover this in testing but its not getting covered. can anyone suggest some way to cover those fields.

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,
        });
      }
    }

I have written test case like:

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,
          })
        );
      });
    });

Solution

  • The sagaHelper only advances the saga by one effect at a time when calling it - so the generator stops executing after yielding the put effect. In order for the saga to run to completion (and thus executing the uncovered lines), it needs to be called one more time. You can also check that the result is undefined to ensure that the saga has run to completion, something like:

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

    With that addition, here is the full test:

    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();
          });
        });