测试React HOC的特性

Testing a property of a React HOC

本文关键字:HOC React 测试      更新时间:2023-09-26

假设我有一个这样的HOC:

const myHoc = ComposedComponent => class Hoccomp extends Component {
  componentWillMount() {
    this.foo = 'bar';
  }
  render() {
    return (
      <ComposedComponent {...this.props}/>
    );
  }
};

如何运行测试来确定this.foo === 'bar'?我目前正在使用react-addons-test-utils,但我对任何解决方案都持开放态度,只要我能在节点环境中运行它。

组件是函数和类。您可以简单地实例化一个并调用该方法,然后检查该实例。

但是,如果进行浅层渲染,则可以调用getMountedInstance()来访问创建的组件并以这种方式对其进行测试。例如:

var shallowRenderer = ReactTestUtils.createRenderer();
shallowRenderer.render( <myHoc /> );
expect( shallowRenderer.getMountedInstance().foo ).toEqual( 'bar' );

然而,请确保两件事:(1)您不仅仅是在测试内部实现细节,也就是说,您正在测试暴露的;以及(2)您确实确信在this上设置一个变量是您想要的,而不是传递props,后者允许您的组合组件是纯的和无状态的。作为后者的一个例子:

const Bare = ({ bar }) => (
  <h1>
    foo = {bar}
  </h1>
);
const Hoc = Component => class Hoc extends Component {
  componentWillMount () {
    this.foo = 'bar';
  }
  render () {
    return ( <Component {...this.props} foo={this.foo} /> );
  }
}
// use the hoc
const Wrapped = Hoc( Bare );
ReactDOM.render( <Wrapped />, document.getElementById( 'app' ) );

这对两个组件来说都更清洁、更容易测试。测试this.foo没有多大意义,因为我们想要测试foo是否作为道具通过——内部实现与良好的单元测试无关。

也就是说,在某些情况下,您希望测试指定的属性。在这种情况下,只要确保这是你想要的。