Redux-testing

提供:Dev Guides
移動先:案内検索

Redux-テスト

Reduxコードのテストは、ほとんどの場合関数を作成するため簡単であり、それらのほとんどは純粋です。 そのため、モックすることなくテストできます。 ここでは、テストエンジンとしてJESTを使用しています。 ノード環境で機能し、DOMにアクセスしません。

以下に示すコードでJESTをインストールできます-

npm install --save-dev jest

バベルでは、次のように babel-jest をインストールする必要があります-

npm install --save-dev babel-jest

そして、次のように.babelrcファイルでbabel-preset-env機能を使用するように設定します-

{
   "presets": ["@babel/preset-env"]
}
And add the following script in your package.json:
{
  //Some other code
   "scripts": {
     //code
      "test": "jest",
      "test:watch": "npm test -- --watch"
   },
  //code
}

最後に、 npm testまたはnpm run test を実行します。 アクションクリエーターとリデューサーのテストケースを作成する方法を確認しましょう。

アクションクリエーター向けのテストケース

以下に示すように、アクション作成者がいると仮定しましょう-

export function itemsRequestSuccess(bool) {
   return {
      type: ITEMS_REQUEST_SUCCESS,
      isLoading: bool,
   }
}

このアクション作成者は、以下のようにテストできます-

import *as action from '../actions/actions';
import* as types from '../../constants/ActionTypes';

describe('actions', () => {
   it('should create an action to check if item is loading', () => {
      const isLoading = true,
      const expectedAction = {
         type: types.ITEMS_REQUEST_SUCCESS, isLoading
      }
      expect(actions.itemsRequestSuccess(isLoading)).toEqual(expectedAction)
   })
})

レデューサーのテストケース

アクションが適用されると、reducerは新しい状態を返す必要があることを学びました。 そのため、リデューサーはこの動作でテストされます。

以下に示すような減速機を検討してください-

const initialState = {
   isLoading: false
};
const reducer = (state = initialState, action) => {
   switch (action.type) {
      case 'ITEMS_REQUEST':
         return Object.assign({}, state, {
            isLoading: action.payload.isLoading
         })
      default:
         return state;
   }
}
export default reducer;

上記の減速機をテストするには、減速機に状態とアクションを渡し、以下に示すように新しい状態を返す必要があります-

import reducer from '../../reducer/reducer'
import * as types from '../../constants/ActionTypes'

describe('reducer initial state', () => {
   it('should return the initial state', () => {
      expect(reducer(undefined, {})).toEqual([
         {
            isLoading: false,
         }
      ])
   })
   it('should handle ITEMS_REQUEST', () => {
      expect(
         reducer(
            {
               isLoading: false,
            },
            {
               type: types.ITEMS_REQUEST,
               payload: { isLoading: true }
            }
         )
      ).toEqual({
         isLoading: true
      })
   })
})

テストケースの作成に慣れていない場合は、https://jestjs.io/[JEST]の基本を確認できます。