React.js: Testing setState’s callback

Tj Hubert
Tj Hubert
Aug 26, 2017 · 1 min read

React’s setStateasynchronous behavior might pose another difficulty to test a component. Luckily, setState, comes with an optional second parameter for a callback. And with the power of stubbing, setState’s callback can be made synchronous in test.

SomeComponent.js

...
onSubmit() {
this.setState({count: this.state.count + 1},
this.props.onSubmitCallback()
);
}
...

SomeComponent.test.js

const setState = sinon.stub(SomeComponent.prototype, ‘setState’)
.callsFake( (newState, callback) => { callback() });
const onSubmitCallback = sinon.spy();
const component =
shallow(<SomeComponent onSubmitCallback={onSubmitCallback}/>);
component.instance().onSubmit();expect(setState).to.be.calledOnce; //PASS!
expect(onSubmitCallback).to.be.calledOnce; //PASS!

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade