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)
})
})
Reducers 测试用例
我们了解到,当应用操作时,reducer 应该返回一个新状态。 因此,reducer 对此行为进行了测试。
考虑如下所示的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;
为了测试上面的reducer,我们需要将state和action传递给reducer,并返回一个新的state,如下所示 −
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的基础知识。

