【问题标题】:Enzyme/ReactJS: How to find specific child componentEnzyme/ReactJS:如何找到特定的子组件
【发布时间】:2017-11-07 21:29:24
【问题描述】:

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

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

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

这就是我的组件的 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>
  )

【问题讨论】:

    标签: javascript reactjs enzyme


    【解决方案1】:

    一般find()返回一个数组,所以你必须使用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' } })
    

    【讨论】:

    • 我不能通过给定的道具选择组件吗?在此示例中,有 name 属性...
    • 可以,但您仍然需要使用at(index)first() 来访问元素并模拟事件
    猜你喜欢
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2019-09-28
    • 2017-05-03
    • 2018-11-12
    • 2018-06-20
    • 1970-01-01
    • 2014-08-15
    相关资源
    最近更新 更多