由于我们主要编写函数,因此测试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,如若转载,请注明出处:https://www.web176.com/redux/2221.html
支付宝
微信