这是测试React / Redux应用程序使用Jest和Enzyme进行测试的四部分系列的第三部分,以获得强大的测试解决方案。
系列
- Part 1: Installation & Setup
- Part 2: Testing React Components
- Part 3: Testing Redux Actions (本文)
- Part 4: Testing Redux Reducers
现在我们将开始在Redux方面进行测试,这就是你开始测试业务逻辑和应用程序状态的地方。在应用程序中使用Redux的一个好处是轻松将业务逻辑与渲染分开。
所以让我们跳进来,开始为我们的Redux行动写一些测试。
消除你的 Redux 商店
由于我们安装的redux-mock-store
npm 包,我们可以用两行代码来嘲笑我们的商店。
1[label __tests__/actions/select_actions.test.js]
2import configureStore from 'redux-mock-store';
3
4// Actions to be tested
5import * as selectActions from '../../actions/select_actions';
6
7const mockStore = configureStore();
8const store = mockStore();
9
10// ...
在嘲笑我们的商店后,我们获得了一些非常好的测试助手,如dispatch()
,getActions()
和clearActions()
,我们将下次使用。
dispatch()
方法通过模仿商店发送一个操作. 该操作将存储在实例内部的数组中并执行getActions()
方法返回模仿商店的操作clearActions()
方法清除存储的操作。
保持你的Mock商店无菌
为了确保我们没有从以前的测试中获得结果,我们将写出少量设置代码,以清除我们在运行每个测试之前的所有操作。
1[label __tests__/actions/select_actions.test.js]
2// ...
3
4describe('select_actions', () => {
5 beforeEach(() => { // Runs before each test in the suite
6 store.clearActions();
7 });
8
9 // ...
10
11});
测试你的行动
为了使我们的 Redux 状态得到正确的更新,我们必须确保正确的操作和负载被发送到我们的减速器中. 在我们的测试中,我们将使用 dispatch()
发送操作到我们的伪装商店。
因此,让我们进入我们的选择_行动
测试套件,并添加一些动作测试。
1[label __tests__/actions/select_actions.test.js]
2// ...
3
4describe('selectAvatar', () => {
5 test('Dispatches the correct action and payload', () => {
6 const expectedActions = [
7 {
8 'payload': 1,
9 'type': 'select_avatar',
10 },
11 ];
12
13 store.dispatch(selectActions.selectAvatar(1));
14 expect(store.getActions()).toEqual(expectedActions);
15 });
16});
17
18// ...
一旦你通过了测试,你可以从Jest的Snapshot测试中获益,这有你减少测试代码的额外好处。
1[label __tests__/actions/select_actions.test.js]
2// ...
3
4describe('selectAvatar', () => {
5 test('Dispatches the correct action and payload', () => {
6 store.dispatch(selectActions.selectAvatar(1));
7 expect(store.getActions()).toMatchSnapshot();
8 });
9});
10
11// ...
如果你从第 2 部分的 测试智能组件 部分中回忆起,我建议你将你的操作与你的组件分开测试。
奖金提示!
你可以写一些非常先进的动作测试。我想提供的是,在动作中,更少是更多的。如果你发现自己写了很多复杂的测试,你可能需要重新思考你的Redux架构。
什么是下一步?
在本系列的 部分 1中,我向您展示了如何安装和设置 Jest 和 Enzyme。 在 部分 2中,我涵盖了测试 React 组件。