React: How to stub component methods that use property initializer syntax?

Created on 10 Apr 2017  路  6Comments  路  Source: facebook/react

I'm finally updating my components from React.createClass() to ES6 classes, after seeing the v15.5.0 deprecations. The first error I'm seeing in my tests after running jscodeshift -t react-codemod/transforms/class.js is that some of my sinon.stub() calls are failing because my component methods are now in the ES7(?) property initializer syntax, 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. I imagine the standard ES6 method syntax + a bunch of .bind() calls in the constructor would do the trick, but I'm just not a fan of that approach. I'd love to know if there's a solution with this syntax.

Thanks!

(PS I posted this to stackoverflow but it seems like there's lots more discussion happening here than there these days. Sorry for the x-post 馃槂 )

All 6 comments

+1 on this question. We are running into the same issue.

After looking at the transpiled code, my assumption was correct: fetchSomeData() gets attached to this, not to Foo.prototype. Because of this, stubbing the method before creating the component instance is not possible. My workaround was to stub the action creator (which is what actually does the data fetching) that gets called by fetchSomeData().

We try to use this issue tracker for bug reports and feature requests only. If you have a usage or support question, we recommend checking out one of the great community-driven platforms like Reactiflux, discuss.reactjs.org, or StackOverflow. I know you said you tried StackOverflow, but Reactiflux may be your best option here, they have a somewhat active channel on testing 馃憤

super helpful -- I forgot about the testing channel in Reactiflux. Thanks @aweary!

Can you paste the link to your SO question so that anyone who opens this thread can find it?

Was this page helpful?
0 / 5 - 0 ratings