Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - how to stub component methods that use property initializer syntax?

Tags:

I'm finally updating my components from React.createClass() to ES6 classes. The first error I'm seeing in my tests is that some of my sinon.stub() calls are failing because jscodeshift -t react-codemod/transforms/class.js converted my component methods to use the property initializer proposal, i.e.

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

My question is: how can I stub fetchSomeData() using this new syntax? My tests looks like sinon.stub(Foo.prototype, 'fetchSomeData'); which no longer works, assuming because fetchSomeData isn't on the prototype anymore.

Thanks!

like image 705
mulleady1 Avatar asked Apr 10 '17 19:04

mulleady1


1 Answers

In this example, fetchSomeData() does in fact get attached to this and not to Foo.prototype, so there is absolutely no way to stub the method before creating the instance. The workaround is to move the logic in fetchSomeData() to a different location that can be stubbed. Or use a different syntax to define the method.

like image 159
mulleady1 Avatar answered Sep 23 '22 10:09

mulleady1