使用 Jest 和 Enzyme 测试 React / Redux 应用程序--第 4 部分:测试 Redux 还原器

这是测试React / Redux应用程序使用Jest和Enzyme进行测试的四部分系列的第4部分,以获得强大的测试解决方案。

系列

继续测试 Redux,我们将通过向您展示如何测试您的减速器来完成这个系列。 减速器是 React / Redux 应用程序中完成渲染链的内容。

让我们做吧!

设置测试套件

首先要做的是导入我们想要测试的减速器和我们的行动类型,我们还将继续写下描述()块来封装这个减速器的测试套件。

<$>[注] 操作类型文件导出这些常数到每个操作的字符串值。

 1[label __tests__/reducers/select_reducer.test.js]
 2// Reducer to be tested
 3import selectReducer from '../../reducers/select_reducer';
 4import {
 5  SELECT_AVATAR, // Only ones related to the reducer being tested
 6} from '../../actions/types';
 7
 8describe('select_reducer', () => {
 9  // ...
10});

你可能会注意到我们用于测试操作的设置代码中的一些漏洞,我们没有嘲笑我们的商店,这意味着我们不需要导入``redux-mock-store包,我们也不需要在每次测试前运行clearActions()

测试你的减速器

让我们先测试我们的初始状态. 我们通过将一个愚蠢的动作传入我们的减速器来做到这一点. 我在减速器中有一个交换声明,默认的案例。如果减速器无法识别该动作类型,那么它会返回当前的未修改的状态。

 1[label __tests__/reducers/select_reducer.test.js]
 2
 3// ...
 4
 5describe('INITIAL_STATE', () => {
 6  test('is correct', () => {
 7    const action = { type: 'dummy_action' };
 8    const initialState = { selectedAvatar: 0 };
 9
10    expect(selectReducer(undefined, action)).toEqual(initialState);
11  });
12});
13
14// ...

接下来,让我们测试我们的减压器是否会根据经过承认的行动和负载来修改我们的状态。

 1[label __tests__/reducers/select_reducer.test.js]
 2
 3// ...
 4
 5describe('SELECT_AVATAR', () => {
 6  test('returns the correct state', () => {
 7    const action = { type: SELECT_AVATAR, payload: 1 };
 8    const expectedState = { selectedAvatar: 1 };
 9
10    expect(selectReducer(undefined, action)).toEqual(expectedState);
11  });
12});
13
14// ...

快照

就像操作和组件一样,一旦你通过了测试,你可以利用 Snapshots并剪除几行代码:

 1[label __tests__/reducers/select_reducer.test.js]
 2
 3// ...
 4
 5describe('INITIAL_STATE', () => {
 6  test('is correct', () => {
 7    const action = { type: 'dummy_action' };
 8
 9    expect(selectReducer(undefined, action)).toMatchSnapshot();
10  });
11});
12
13describe('SELECT_AVATAR', () => {
14  test('returns the correct state', () => {
15    const action = { type: SELECT_AVATAR, payload: 1 };
16
17    expect(selectReducer(undefined, action)).toMatchSnapshot();
18  });
19});
20
21// ...

奖金提示!

随时随地将您的减速器组合为相似的功能。我们使用我们的SELECT_AVATAR文件使用了SELECT_AVATAR操作类型,但在同一减速器中可以轻松地添加SELECT_USERSELECT_THEME等功能。通过将它们组合在一起,我们可以改进我们的应用架构。如果它们的功能相似,我们可以应用DRY(https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)原则。我们有更多的机会重复使用代码并写出可以覆盖所有减速器的测试助手。

结论

在本系列的 部分 1中,我向您展示了如何安装和设置 Jest 和 Enzyme。 在 部分 2中,我涵盖了测试 React 组件。

您现在应该有一个圆满的设置和相关知识来测试您的React / Redux应用程序。测试不一定是困难的。

Published At
Categories with 技术
Tagged with
comments powered by Disqus