14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React+Reduxでreducerのテスト

Last updated at Posted at 2015-10-16

#概要

reduxでreducerのテストをしたく、以下の様な記事を書いた。

モックしたデータをstore.dispatchするという方法をとっていたが、これも、reducer実行終了時まで待つ必要があるため、タイミングを担保するのが難しい。そこで、別の方針でテストすることにした。

#方針

reduxのドキュメントを参考にすると、dispatchをせず、直接reducer関数を実行している。同じように実装することにした。

reducer.js

// createReducerは以下の様なutilメソッドを用意しておく
// export function createReducer (initialState, reducerMap) {
//   return (state = initialState, action) => {
//     const reducer = reducerMap[action.type];
//     return reducer ? reducer(state, action.payload) : state;
//   };
// }
import { createReducer } from 'utils';

import {
  REQUEST,
  REQUEST_SUCCESS,
} from 'constants';

const initialState = {
  items: [],
  isFetching: false,
};

export default createReducer(initialState, {
  [REQUEST]: (state) => {
    return {
      ...state,
      isFetching: true,
    };
  },
  [REQUEST_SUCCESS]: (state, action) => {
    return {
      ...state,
      items: action.items,
      isFetching: false,
    };
  },
});

テストは以下のようになった。

reducer.spec.js
import {
  REQUEST,
  REQUEST_SUCCESS,
} from 'constants';
import someReducer from './reducer.js';

describe('(Reducer)', function() {
  const initialState = {
    items: [],
    isFetching: false,
  };

  it('REQUEST', () => {
    expect(
      someReducer(initialState, {
        type: REQUEST,
      })
    ).toEqual({
      items: [],
      isFetching: true,
    });
  });

  it('REQUEST_SUCCESS', () => {
    expect(
      someReducer(initialState, {
        type: REQUEST_SUCCESS,
        items: ['items'],
      })
    ).toEqual({
      items: ['items'],
      isFetching: false,
    });
  });
});

actionのテストよりもシンプルに実装できた。

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?