React, how to simulate user input for unit testing?
You seem to have a bug in your Input component. When event.target.value.length > this.props.maxLength
you never set the actual state, leaving the state.value
as ''
. It seems you expected it to have been set to the value, but truncated to maxLength. You'll need to add that yourself:
handleChange(event) {
/* Check if max length has been set. If max length has been
set make sure the user input is less than max Length, otherwise
return before updating the text string. */
if (this.props.maxLength) {
if (event.target.value.length > this.props.maxLength) {
// ** Truncate value to maxLength
this.setState({ value: event.target.value.substr(0, this.props.maxLength) });
return;
}
}
this.setState({ value: event.target.value });
}
... then, the following test works and passes:
it('Make sure inputted text is shorter than max length', () => {
const result = mount(<Input maxLength={10}></Input>);
result.find('input').simulate('change', { target: { value: '1234567890!!!' } });
expect(result.state().value).to.equal("1234567890");
});