createAsyncThunkのテスト

createAsyncThunkのテストの書き方についてまとめます。

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import {fetchUser, initialState} from './index';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('app_version', () => {
  describe('checkAppVersion', () => {
    it('呼び出したときpenndingのみを返す', async () => {
      const store = mockStore({ appVersion: initialState });
      store.dispatch(targetMethod());
      expect(store.getActions().length).toEqual(1);
      expect(store.getActions()[0].type).toEqual(checkAppVersion.pending.type);
    });
    it('失敗したときpennding後にrejectedを返す', async () => {
      const store = mockStore({ appVersion: initialState });
      mockAppVersionService.prototype.checkAppVersion = () => {
        return new Failure(new ServerError(ErrorMessage.NETWORK_ERROR));
      };
      await store.dispatch(checkAppVersion());
      expect(store.getActions().length).toEqual(2);
      expect(store.getActions()[0].type).toEqual(checkAppVersion.pending.type);
      expect(store.getActions()[1].type).toEqual(checkAppVersion.rejected.type);
      expect(store.getActions()[1].payload).toEqual(ErrorMessage.NETWORK_ERROR);
    });
    it('成功したときpennding後にfulfilledを返す', async () => {
      const store = mockStore({ appVersion: initialState });
      mockAppVersionService.prototype.checkAppVersion = () => {
        return new Success(AppVersion.State.Required);
      };
      await store.dispatch(checkAppVersion());
      expect(store.getActions().length).toEqual(2);
      expect(store.getActions()[0].type).toEqual(checkAppVersion.pending.type);
      expect(store.getActions()[1].type).toEqual(checkAppVersion.fulfilled.type);
      expect(store.getActions()[1].payload).toEqual(AppVersion.State.Required);
    });
  });
});

©Tsurutan. All Rights Reserved.