React Enzyme: Testing componentWillReceiveProps, the Clean Way

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

Most times, I call the same function in componentWillReceiveProps() and in componentWillMount(). When asserting the stubbed function, it is tempting to just expect the function to be called twice. However, this implementation is somewhat dirty as it tests both lifecycle hooks. Thus, making use of sinon’s reset(), which will reset the call count of the stubbed function, makes the test become more modular.

SomeComponent.js

...
componentWillMount() {
this.logUserId(this.props.userId);
}
componentWillReceiveProps(nextProps) {
if (this.props.userId !== nextProps.userId) {
this.logUserId(nextProps.userId);
}
}
logUserId(userId) {
console.log(userId);
}
...

SomeComponent.test.js

import SomeComponent from ‘./SomeComponent’;
import { shallow } from ‘enzyme’;
describe('componentWillReceiveProps()', () => {
it('call logUserId once', () => {
const logUserId =
sinon.stub(SomeComponent.prototype, ‘logUserId’);
let userId = '123';
const component = shallow(<SomeComponent userId={userId}/>;
// resetting call count from componentWillMount()
logUserId.reset();
userId = '456';
// triggers componentWillReceiveProps
component.setProps({ userId });
// PASS!
expect(logUserId).to.be.calledOnce.and.calledWith(userId);
})
})

)
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