简体   繁体   English

如何通过将Redux连接的React组件导出为PureComponent来测试它?

[英]How do you test a redux connected react component by exporting it as a PureComponent?

I've been looking for a solution that I know works but syntax is tripping me up. 我一直在寻找一种我知道可行的解决方案,但是语法使我感到困惑。 Here's the scenario: 这是场景:

You have a redux connected component that is exported like so: 您有一个Redux连接的组件,其导出方式如下:

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

You need to test that component and not see this error in Enzyme: 您需要测试该组件,而在酶中看不到此错误:

Could not find "store" in either the context or props of "Connect(componentToExport)"

The solution looks something like the following. 解决方案如下所示。

At the bottom of the component being tested you have: 在要测试的组件的底部,您可以:

export default connect(mapStateToProps, mapDispatchToProps)(componentToExport);
export default componentToExport as PureComponentToExport

I've tried using: 我试过使用:

import from React, { PureComponent } 

and then creating the component with 然后用创建组件

extends PureComponent 

but that's not working as expected. 但这不能按预期工作。 Enzyme should really have this covered in the docs :/ 酶确实应该在文档中对此进行介绍:/

Any help is greatly appreciated. 任何帮助是极大的赞赏。 I don't want to include an external library, or pass the store into the component being tested etc. I'd like to be able to use this syntax that I've seen work before. 我不想包含一个外部库,也不想将存储传递到正在测试的组件中。我希望能够使用以前见过的这种语法。

thanks :) 谢谢 :)

The way to do it is to also export the unconnected component, eg by adding export to its definition or by using an explicit export: 做到这一点的方法是还导出未连接的组件,例如通过在其定义中添加export或使用显式导出:

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

And then import it in your test with a named import like so 然后使用如下所示的命名导入将其导入您的测试中

import { YourComponent } from '../YourComponent';

There's some more information about testing connected components in the redux docs . redux docs中有关于测试连接的组件的更多信息。

import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import ChildComponent from './ChildComponent';


export class YourComponent extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <ChildComponent/>
    );
  }
}

function mapStateToProps(state, ownProps) {
  return {
    state,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
    yourActionsGoHere,
    },
    dispatch
  );
}

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

In your Enzyme test you'll want: 在酶测试中,您需要:

import { YourComponent } from '../YourComponent';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM