redux 내에서 외부 라이브러리를 mock 하기

곽형조 (KCena)·2020년 12월 31일
0

내가 하고싶었던 것

내가 진행하던 프로젝트에서 로그인, 회원가입, 로그아웃 요청 이후 홈 페이지로 이동하는 기능을 작성하고 싶었다. 아래와 같이 로그아웃을 요청하는 비동기 요청이 있다.

export function requestLogout() {
  return async (dispatch) => {
    await postLogout();

    dispatch(setUser(initialUser));
    dispatch(push('/'));
    deleteItem('user');
  };
}

postLogout api를 이용해 로그아웃 한 뒤, 유저 정보를 초기화 한다.

여기서 push를 이용하는 것을 볼 수 있는데, 이는 connected-react-router 패키지를 사용 한 것이다.

connected-react-routerredux 내에서 react-router 기능을 사용할 수 있도록 해 주는 패키지이다. redux-thunk와 함께 사용하여 각종 history 메소드를 이용해 페이지를 이동할 수 있다.

문제는 테스트에서 외부 패키지의 push를 몰라 테스트가 깨진다는 것이다.

내가 해결한 방법

이는 mocking으로 해결할 수 있다. 외부 패키지의 push를 가짜로 대체하여 내가 테스트 하고자 하는 것에 집중하는 것이다. 난 이동하고자 하는 url 경로와 함께 push가 잘 호출되는지 확인하고 싶었다.

describe('requestLogout', () => {
  beforeEach(() => {
    store = mockStore({
      authReducer: {
        user: logInUser,
      },
    });
  });

  it('dispatchs logout and change url path', async () => {
    await store.dispatch(requestLogout());

    const actions = store.getActions();

    expect(actions[0]).toEqual(setUser(logOutUser));
    expect(actions[1]).toEqual(push('/'));
  });
});

위와 같이 테스트 코드를 작성하고 이제 push를 mocking 한다.
먼저 맨 위에 push를 import 한다.

import { push } from 'connected-react-router'

mocking 하고자 하는 외부 패키지를 파일 경로의 최 상단에 __mocks__ 폴더를 만들고 그 안에 파일 이름으로 connected-react-router.js 를 만든다.

그리고 push 메소드를 mocking 한다. 이는 connected-react-router 패키지의 테스트 코드를 참고하였다.

export const push = jest.fn((pathname) => ({
  type: 'LOCATION_CHANGE',
  payload: {
    location: {
      pathname,
    },
    action: 'PUSH',
  },
}));

결과

테스트가 잘 통과되었다.

sources

0개의 댓글