I have some problems with testing events for nested components. This is how my component tree look like:
- ModalComponent (Stateful with value for Input and update handler)
- - ModalType (stateless, passes value and update down to input)
- - - Input (stateless)
I have the value state and the handler for updating my value in my ModalComponent. This information just passed down through ModalType to my Input element via props.
I have tried to mount my ModalComponent with enzyme, find my input and simulate a change on the element. But this did not work.
What is the best strategy to test nested component when the handler and state are n parents components above?
EDIT I have created a lean demo setup of my component in a separate blank react project
class App extends Component {
state = {
inputs: {
machineName: 'Empty'
}
}
onChangeHandler = (e) => {
let updatedState = null
console.log(e.target.value, e.target.id);
switch (e.target.id) {
case 'machineName':
updatedState = { ...this.state.inputs, machineName: e.target.value }
this.setState({inputs: updatedState})
break;
default:
break;
}
}
render() {
return (
<div className="App">
<ModalType onChange={this.onChangeHandler} value={this.state.inputs}></ModalType>
</div>
);
}
}
const ModalType = (props) => {
return <Input onChange={props.onChange} value={props.value.machineName}></Input>
}
const Input = (props) => (
<input id="machineName" onChange={props.onChange} value={props.value}></input>
)
My testing script
test('should handle change on input', () =>{
const wrapper = mount(<App/>)
wrapper.setState({inputs: { machineName: 'Empty' }})
wrapper.find('input').simulate('focus')
wrapper.find('input').simulate('change', {target: {value: '123'}})
wrapper.update()
// fails
expect(wrapper.state().inputs.machineName).toEqual('123')
// fails too
expect(wrapper.find('input').props().value).toEqual('123')
})
Thanks!
const wrapper = mount(<ModalComponent />);
const input = wrapper.find('input');
const event = {target: {value: 'testValue'}};
input.simulate('change', event);
The code above is a working example of how to simulate a change event on your input.
Edit
Your event is not correct. Since your handler is doing something only if the target id is machineName, you need to add that id to your mock event.
wrapper.find('input').simulate('change', {target: {value: '123', id: 'machineName'}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With