What is the correct way of unit testing a React component prop update.
Here is my test fixture;
describe('updating the value', function(){
var component;
beforeEach(function(){
component = TestUtils.renderIntoDocument(<MyComponent value={true} />);
});
it('should update the state of the component when the value prop is changed', function(){
// Act
component.props.value = false;
component.forceUpdate();
// Assert
expect(component.state.value).toBe(false);
});
});
This works fine and the test passes, however this displays a react warning message
'Warning: Dont set .props.value of the React component <exports />. Instead specify the correct value when initially creating the element or use React.cloneElement to make a new element with updated props.'
All i want to test is the update of a property, not to create a new instance of the element with a different property. Is there a better way to do this property update?
AirBnB's Enzyme library provides an elegant solution to this question.
it provides a setProps method, that can be called on either a shallow or jsdom wrapper.
it("Component should call componentWillReceiveProps on update", () => {
const spy = sinon.spy(Component.prototype, "componentWillReceiveProps");
const wrapper = shallow(<Component {...props} />);
expect(spy.calledOnce).to.equal(false);
wrapper.setProps({ prop: 2 });
expect(spy.calledOnce).to.equal(true);
});