react icon indicating copy to clipboard operation
react copied to clipboard

How to stub component methods that use property initializer syntax?

Open mulleady1 opened this issue 9 years ago • 6 comments

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 😃 )

mulleady1 avatar Apr 10 '17 20:04 mulleady1

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

nomadtechie avatar Apr 21 '17 17:04 nomadtechie

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().

mulleady1 avatar Apr 21 '17 17:04 mulleady1

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 👍

aweary avatar Apr 21 '17 21:04 aweary

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

nomadtechie avatar Apr 21 '17 21:04 nomadtechie

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

gaearon avatar Apr 23 '17 10:04 gaearon

Can do.

http://stackoverflow.com/questions/43331611/react-how-to-stub-component-methods-that-use-property-initializer-syntax

mulleady1 avatar Apr 23 '17 14:04 mulleady1