Enzyme/ReactJS: 如何找到特定的子组件

Enzyme/ReactJS: How to find specific child component

我正在尝试对组件进行 enzyme/jest 单元测试。我需要模拟特定子组件的更改事件(因为有两个)。

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' })

但这不是找到两个输入组件的正确方法...

我的组件的 render() 函数是这样的:

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>
  )

通常 find() returns 一个数组,所以你必须使用 at(index)first() 来访问特定元素:

http://airbnb.io/enzyme/docs/api/ShallowWrapper/at.html http://airbnb.io/enzyme/docs/api/ShallowWrapper/first.html

在您的情况下,您还可以导入 Input 组件并像这样找到它们:

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' } })