【问题标题】:React - how to stub component methods that use property initializer syntax?React - 如何存根使用属性初始化器语法的组件方法?
【发布时间】:2017-09-05 23:53:44
【问题描述】:

我终于将我的组件从 React.createClass() 更新为 ES6 类。我在测试中看到的第一个错误是我的一些sinon.stub() 调用失败了,因为jscodeshift -t react-codemod/transforms/class.js 将我的组件方法转换为使用属性初始化器提议,即

class Foo extends React.Component {
  componentWillMount() {
    this.fetchSomeData(this.props);
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.someProp !== this.props.someProp) {
      this.fetchSomeData(nextProps);
    }
  }
  fetchSomeData = (props) => {
    ...
  };
  render() {
    ...
  }
}

我的问题是:如何使用这种新语法来存根 fetchSomeData()?我的测试看起来像 sinon.stub(Foo.prototype, 'fetchSomeData'); 不再有效,假设因为 fetchSomeData 不再在原型上。

谢谢!

【问题讨论】:

  • ES7 于去年(2016 年)发布。属性初始化器是一个proposal
  • 您的测试是否可以访问组件的实例?如果是这样你可以做 sinon.stub(componentInstance, 'fetchSomeData') 然后 componentInstance.render();
  • @jeznag 好点,谢谢。没想到。但是我让酶处理渲染生命周期,我认为干预这对我来说不是一个好的解决方案。

标签: reactjs sinon ecmascript-next


【解决方案1】:

在这个例子中,fetchSomeData() 实际上是附加到 this 而不是 Foo.prototype,所以在创建实例之前绝对没有办法存根方法。解决方法是将fetchSomeData() 中的逻辑移动到可以存根的不同位置。或者使用不同的语法来定义方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多