【问题标题】:How to test component that contains a component connected to Redux in Enzyme / React?如何在 Enzyme / React 中测试包含连接到 Redux 的组件的组件?
【发布时间】:2019-03-10 04:03:17
【问题描述】:

Enzyme 中测试连接到 ReduxReact 组件 时有一个熟悉的问题。你可能遇到了这个错误:

Invariant Violation: Could not find "store" in either the context or props of "Connect(YourComponent)

通过两次导出被测组件解决

export class YourComponent extends Component {}
export default connect(mapStateToProps, mapDispatchToProps)(YourComponent);

在您的测试中将 YourComponent 作为对象导入

import { YourComponent } from '../pathToYourComponent'

我遇到了一个关于这个问题的新场景。 我正在测试一个连接组件,并且我正在使用上面的解决方案来解决该问题,但是在该组件内部还有另一个连接组件会在某些道具存在时呈现。

import React, { Component } from 'react';
export class YourComponent extends Component {
  constructor(props) {
    super(props)
  }
  render() {
    const { arrayOfObjects } = this.props;

    let nestedConnectedComponent; 
    if (arrayOfObjects.length) {
      nestedConnectedComponent = arrayOfObjects.map((ele, idx) => (
        <NestedConnectedComponent
          key={idx}
        />
      ))
    }
    return (
      <div> {arrayOfObjects} </div>
    )
  }
}

function mapStateToProps(){}
function mapDispatchToProps(){}

export default connect(mapStateToProps, mapDispatchToProps)(YourComponent);

在测试包含连接到 redux 的组件的组件时,如何避免“找不到存储”错误?

组件在最新版本的 Enzyme 中被 shallow 渲染。

【问题讨论】:

    标签: javascript reactjs sinon enzyme


    【解决方案1】:

    如果您使用浅层渲染,则不会出现此错误,来自 docs

    '浅渲染有助于限制自己将组件作为一个单元进行测试,并确保您的测试不会间接断言子组件的行为。'

    【讨论】:

    • 这是不正确的。并不是在 ChildComponents 上断言行为,而是 ChildComponent 连接到 redux,不管我在测试中只使用了浅层。在这里讨论:github.com/airbnb/enzyme/issues/183
    • 为什么?我正在使用浅渲染对文档中提到的组件进行单元测试,并且不会渲染子级,因此没有错误“找不到存储”
    • 这不是浅渲染的行为,请查看 reactjs.org/docs/shallow-renderer.html。如果你浅渲染一个组件,它的子组件将不会被渲染或实例化。你能粘贴你的测试代码来检查吗?
    • 您提到的问题已经关闭,可能您使用的是旧版本的酶。我正在使用酶 3.6,但我从未遇到过这个问题。
    • 我小时候刚写了一个带有连接组件的组件测试(来自redux react training)。你可以看到,浅层渲染测试很好,不需要提供存储。 codesandbox.io/s/2pqwq12j9y(见测试,测试文件为/src/Dummy.test.js)
    猜你喜欢
    • 2020-03-30
    • 2018-03-12
    • 2017-11-26
    • 2020-01-23
    • 2017-03-29
    • 2019-05-26
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多