Reputation: 17332
I am trying to do a enzyme/jest unit test for a component. I need to simulate a change event of a specific child component (as there are two of them).
const wrapper = shallow(<CreateAccount />)
wrapper.find({ name: 'username' }).simulate('change', { target: { value: 'Username' } })
wrapper.find({ password: 'password' }).simulate('change', { target: { value: 'Password' } })
const state = wrapper.instance().state
expect(state).toEqual({ username: 'Username', password: 'Password' })
But this is not the correct way to find both Input components...
This is how my render() function of my component looks like:
render () {
return (
<Form onSubmit={this._onSubmit.bind(this)}>
<Input
value={this.state.description}
onChange={this._onChange.bind(this)}
name='username'
type='text'
placeholder='Username'
/>
<Input
value={this.state.url}
onChange={this._onChange.bind(this)}
name='password'
type='password'
placeholder='Password'
/>
<Button type='submit'>
Submit
</Button>
</Form>
)
Upvotes: 0
Views: 5802
Reputation: 752
In general find()
returns an array so you have to use at(index)
or first()
to access specific element:
http://airbnb.io/enzyme/docs/api/ShallowWrapper/at.html http://airbnb.io/enzyme/docs/api/ShallowWrapper/first.html
In your case you can also import Input
component and find them like this:
import Input from 'input-component-path'
...
wrapper.find(Input).at(0).simulate('change', { target: { value: 'Username' } })
wrapper.find(Input).at(1).simulate('change', { target: { value: 'Password' } })
Upvotes: 3