Categories: Redux教程

Redux教程:测试

由于我们主要编写函数,因此测试Redux代码很容易,而且大多数函数都是纯函数。因此,我们甚至可以在不模拟它们的情况下对其进行测试。在这里,我们使用JEST作为测试引擎。它在节点环境中工作,并且不访问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) 
   })
})

减速器测试用例

我们已经了解到,应用动作时,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
      })
   })
})

如果您不熟悉编写测试用例,则可以检查JEST的基础知识。

terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

1 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

2 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

3 周 ago