Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API, slices 테스트 코드 사용법 #41

Open
seuha516 opened this issue Nov 4, 2022 · 0 comments
Open

API, slices 테스트 코드 사용법 #41

seuha516 opened this issue Nov 4, 2022 · 0 comments
Assignees
Labels

Comments

@seuha516
Copy link
Contributor

seuha516 commented Nov 4, 2022

apis.test.ts

import client from './client';
import * as userAPI from './user';
import * as chatAPI from './chat';
// 사용할 API 경로 추가

beforeEach(() => {
  client.get = jest.fn().mockImplementation(url => Promise.resolve({ data: url }));
  client.post = jest.fn().mockImplementation(url => Promise.resolve({ data: url }));
  client.put = jest.fn().mockImplementation(url => Promise.resolve({ data: url }));
  client.delete = jest.fn().mockImplementation(url => Promise.resolve({ data: url }));
});
afterAll(() => jest.restoreAllMocks());

const loginRequest = {
  username: '11111111',
  password: '11111111',
};
// 적당한 더미 데이터 생성

describe('API TEST', () => {
  describe('User', () => {
    test('token', async () => {
      const result = await userAPI.token(); // API를 호출하면 mock에 의해 주소가 반환됨
      expect(result).toBe(`/api/user/token/`); // 맞는지 체크
    });
    ........

chat.test.ts

import { configureStore } from '@reduxjs/toolkit';
import { call } from 'redux-saga/effects';
import { expectSaga } from 'redux-saga-test-plan';
import { throwError } from 'redux-saga-test-plan/providers';
import { rootReducer } from '../index';
import * as chatAPI from '../apis/chat'; // 사용할 API 경로 추가
import chatSaga, { initialState, chatSlice, chatActions } from './chat'; // Saga, initialState, Slice, Action 가져오기

const simpleError = new Error('error!');

jest.spyOn(global, 'alert').mockImplementation(msg => msg);

describe('slices - chat', () => {
  test.each([
    // 배열 추가
    // 1번째 칸: Actions에서 호출할 부분
    // 2번째 칸: 그로 인해 변경되고 난 후의 state
    [chatActions.setSocket('socket'), { ...initialState, socket: 'socket' }],
    [chatActions.getChatroomList('11111111'), initialState],
    [chatActions.getChatroomListSuccess('data'), { ...initialState, chatroomList: 'data' }],
    [chatActions.getChatroomListFailure('error'), { ...initialState, error: 'error' }],
    [chatActions.getMessageList('11111111'), initialState],
    [chatActions.getMessageListSuccess('data'), { ...initialState, messageList: 'data' }],
    [chatActions.getMessageListFailure('error'), { ...initialState, error: 'error' }],
  ])('reducer', (action, state) => {
    const store = configureStore({
      reducer: rootReducer,
    });
    store.dispatch(action);
    expect(store.getState().chat).toEqual(state); // chat를 적절히 변경
  });

  describe('saga success', () => {
    // Success 처리가 필요한 경우, 아래 블록 추가
    test('getChatroomList', () => {
      return expectSaga(chatSaga)
        .withReducer(chatSlice.reducer) // 관련된 리듀서
        .provide([[call(chatAPI.getChatroomList, '11111111'), 'data']]) // 해당 API를 '11111111'을 넣어서 call했을 때, 중간에서 가로챈 후 'data'를 반환하게 함
        .put({ type: 'chat/getChatroomListSuccess', payload: 'data' }) // 예측되는 결과. data를 동반한 Success 액션이 실행되는 지 테스트하는 것이 목적
        .dispatch({ type: 'chat/getChatroomList', payload: '11111111' }) // 디스패치할 액션 입력
        .hasFinalState({ ...initialState, chatroomList: 'data' }) // 모든 작업이 끝난 후 예상되는 state. 테스트되는 부분
        .silentRun();
    });
  });

  describe('saga failure', () => {
    // Failure 처리가 필요한 경우, 아래 블록 추가
    test('getChatroomList', () => {
      return expectSaga(chatSaga)
        .withReducer(chatSlice.reducer)
        .provide([[call(chatAPI.getChatroomList, '11111111'), throwError(simpleError)]]) // 중간에서 가로챈 후 에러를 반환하게 함
        .put({ type: 'chat/getChatroomListFailure', payload: simpleError }) // 예측되는 결과(실패)
        .dispatch({ type: 'chat/getChatroomList', payload: '11111111' })
        .hasFinalState({ ...initialState, error: simpleError })
        .silentRun();
    });
  });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants