SoYoung210 / soso-tip

🍯소소한 팁들과 정리, 버그 해결기를 모아두는 레포
24 stars 0 forks source link

redux-saga Fail test code 작성법 #41

Open SoYoung210 opened 4 years ago

SoYoung210 commented 4 years ago

Desc

redux-saga에서 error throw하는 TestCode를 작성하는 법.

실제 api 호출 구조와 맞게 error response를 mocking해주어야 한다.

export const requestPOST = async (
 ...options
) => {
  try {
    const response = await axiosInstance.post(url, data, { params, headers });

    return response.data;
  } catch (error) {
    throw error.response;
  }
};

export function* exampleSaga() {
  try {
    // ... success action
  } catch (e) {
    yield put(testActions.fail(e.status)
  }
}

위와 같이 작성되었을 때, mocking 해야 하는 Error의 구조는 다음과 같다.

const testError = {
      status: FetchStatusCode.UNKNOWN,
};

status필드가 있도록 작성되어야 한다. 만약 testError에 string이나 다른 값을 넣을 경우 test수행시 payload: undefined에러로 테스트가 실패한다.

Test Case

it('should dispatch fail action', async () => {
    // Given
    const testError = {
      status: FetchStatusCode.UNKNOWN,
    };
    const gen = testSaga();
    // Then
    expect(gen.next(EMPTY_REQUEST as any).value).toEqual(
      call(getSampleApi, (EMPTY_REQUEST as any))
    );
    expect(gen.throw(testError).value).toEqual(
      put(testActions.fail(testError.status))
    );
    expect(gen.next().done).toBeTruthy();
  });