将事件对象传递给酶.simulate

Sea*_*lus 19 javascript reactjs jestjs enzyme

我正在使用Jest和Enzyme来测试React复选框组件.

这是我的测试:

it('triggers checkbox onChange event', () => {
  const configs = {
    default: true,
    label: 'My Label',
    element: 'myElement',
  }
  const checkbox = shallow(
    <CheckBox
      configs={configs}
    />
  )
  checkbox.find('input').simulate('click')
})
Run Code Online (Sandbox Code Playgroud)

我在运行测试时遇到此错误:

TypeError: Cannot read property 'target' of undefined
Run Code Online (Sandbox Code Playgroud)

这是我的组件的输入:

<div className="toggle-btn sm">
  <input 
    id={this.props.configs.element} 
    className="toggle-input round" 
    type="checkbox" 
    defaultChecked={ this.props.defaultChecked } 
    onClick={ e => this.onChange(e.target) }
  >
  </input>
</div>
Run Code Online (Sandbox Code Playgroud)

我需要通过一个事件作为第二个对象simulate,但我不知道如何做到这一点.

谢谢

mad*_*ox2 42

simulatefunction接受将传递给事件处理程序的其他参数.你可以嘲笑你的活动.例如:

const mockedEvent = { target: {} }
checkbox.find('input').simulate('click', mockedEvent)
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,这会导致“TypeError: Cannot set property target of #&lt;Event&gt; that has only a getter” (2认同)