React - 如何存根使用属性初始值设定项语法的组件方法



我终于将我的组件从 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因为它不再在原型上。

谢谢!

在此示例中,fetchSomeData()实际上确实附加到this而不是Foo.prototype,因此在创建实例之前绝对无法存根该方法。解决方法是将fetchSomeData()中的逻辑移动到可以存根的其他位置。或者使用不同的语法来定义方法。

最新更新