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 的基础知识。
广告