Redux - 測試



測試 Redux 程式碼非常簡單,因為我們主要編寫的都是函式,並且大多數都是純函式。因此,我們甚至無需模擬它們即可進行測試。在此,我們使用 JEST 作為測試引擎。它在 Node 環境中執行,不會訪問 DOM。

我們可以使用以下給出的程式碼安裝 JEST −

npm install --save-dev jest

使用 Babel 時,需要如下所示安裝 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) 
   })
})

歸約器的測試用例

我們已瞭解,當應用動作時,歸約器應返回一個新的狀態。因此,歸約器將針對這種行為進行測試。

請考慮如下所示的歸約器 −

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
      })
   })
})

如果你不熟悉編寫測試用例,可以檢視 JEST 的基礎知識。

廣告