简体   繁体   English

酶/ ReactJS:如何查找特定的子组件

[英]Enzyme/ReactJS: How to find specific child component

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()函数的样子:

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

In general find() returns an array so you have to use at(index) or first() to access specific element: 通常, find()返回一个数组,因此您必须使用at(index)first()来访问特定元素:

http://airbnb.io/enzyme/docs/api/ShallowWrapper/at.html http://airbnb.io/enzyme/docs/api/ShallowWrapper/first.html 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: 您还可以导入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' } })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM