【问题标题】:Enzyme/Jest React Testing - Shallow connected component with react-redux > 6Enzyme/Jest React 测试 - react-redux > 6 的浅连接组件
【发布时间】:2020-03-30 03:32:46
【问题描述】:

我们使用 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 吞下连接组件的最佳方法是什么

【问题讨论】:

    标签: reactjs unit-testing react-redux jestjs enzyme


    【解决方案1】:

    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 提出修复。

    【讨论】:

    • 让我走上了正确的道路。我必须在 setupTests.js 中做 jest.mock('react-redux', () => { return require('react-redux-test'); }) 。出于某种原因,如果它位于 mocks 文件夹下,它就不起作用。
    【解决方案2】:

    shallow 在 redux 7 上确实可以工作,但实现发生了变化。 所以而不是

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

    你现在做

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 2017-02-12
      • 2020-11-20
      • 2017-03-11
      • 2019-01-27
      • 2019-01-28
      • 2018-08-20
      • 1970-01-01
      • 2018-08-28
      相关资源
      最近更新 更多