I have a React Component that implements the shouldComponentUpdate method and I\'d like to unit test it. Ideally I could change some prop or state on the component in a unit tes
You probably dont want to test shouldComponentUpdate
as isolated function when you already know what the outcome is.
As it mentioned in the documentation you can use setProps
or setState
and this is probably - at least for me - a better approach to expect the exact outcome from your component when updating related values.
In your MyComponent.test.js
import { expect } from 'chai';
import sinon from 'sinon-sandbox';
import { shallow } from 'enzyme';
it('updates when changing state or props', () => {
const wrapper = shallow( );
const shouldComponentUpdate = sinon.spy(MyComponent.prototype, 'shouldComponentUpdate');
expect(shouldComponentUpdate).to.have.property('callCount', 0);
wrapper.setProps({ propThatWillUpdateTheComp: 'foo' });
// or in case you are testing component update in case of state change
// wrapper.setState({ stateThatWillUpdateTheComp: 'bar' });
expect(shouldComponentUpdate).to.have.property('callCount', 1);
expect(shouldComponentUpdate.returned(true)).to.be.equal(true);
});