React Enzyme: Testing componentWillReceiveProps, the Clean Way
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);
})
})
