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!