酶/Jest react测试 - 具有 react-redux > 6 的浅连接组件

IT技术 reactjs unit-testing react-redux jestjs enzyme
2021-05-16 12:17:40

我们使用 Enzyme 和 Jest 进行测试。在我们的代码库中更新到最新版本的 react-redux,并且所有连接的组件测试用例开始失败(版本 6)。使用

import { createMockStore } from 'redux-test-utils';

创建商店

适用于旧版本的测试用例:

const wrapper = shallow(<SomeConnectedComponent />, {context: { store }});

这失败给出错误

不变违规:在“Connect(SomeConnectedComponent)”的上下文中找不到“store”。

阅读了几篇文章,得到了使用提供程序包装器安装和包装的建议

const wrapper = mount(<Provider store={store}><SomeConnectedComponent /></Provider>);

上面的代码有效,但我希望它与吞咽一起用于单元测试。

编辑 :

const wrapper = shallow(<Provider store={store}>
<SomeConnectedComponent />
</Provider>)

上面的代码返回空的shallowWraper 对象。

使用 react-redux 版本 > 6 吞下连接组件的最佳方法是什么

2个回答

Shallow 不适用于最新版本的 react-redux。从版本 6.x 开始,它会导致上述问题。

我发现的最佳解决方案是使用旧版本的 react-redux 进行测试,使用较新版本的实际代码。

1)将旧版本添加为开发依赖项。因为有较新版本的 react-redux,所以您需要使用别名。这可以是任何版本 5.x 这将安装“react-redux-test”

yarn add react-redux-test@npm:react-redux@5.0.6 -D

2) 在 _ mocks _ 文件夹下,创建一个新文件 react-redux.js 并从里面导出旧版本

export * from 'react-redux-test';

默认情况下,这个模拟将在每个测试用例文件中使用,因此旧的测试代码不再中断。

但是,如果您想使用新的 react-redux 库进行测试,则可以使用

jest.unmock('react-redux')

在新的测试文件上方。

升级后有数百个测试失败,这种方法对我有用,因为我也想在新组件中使用 Hooks Api。

通过这种方式,您可以使用新库的功能,直到酶 / react-redux 提出修复方案。

浅在 redux 7 上确实有效,但实现发生了变化。所以而不是

const wrapper = shallow(<Provider store={store <SomeConnectedComponent/></Provider>)

你现在做

const wrapper = shallow(<SomeConnectedComponent store={store}/>)

不再需要包装在提供者中,并防止不必要的潜水。然后,您可以像这样遍历浅层包装器:

wrapper.children().dive().find(<ChildComponent>))