简体   繁体   中英

Triggering this.props.dispatch in a test environment

Hello I have a Jest / Enzyme test like this:

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

And a component that looks like this:

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

Clicking on the input causes this method to be called:

this.props.dispatch(update(data))

It works okay in my browser, however when testing the onClick event I get this error:

TypeError: this.props.dispatch is not a function

How do I get this.props.dispatch to work in my test?

Thanks

You need to pass dispatch as a prop in your test.

Modified code below:

it('triggers checkbox onChange event', () => {
  const configs = {
    default: true,
    label: 'My Label',
    element: 'myElement',
  }

  const dispatch = jest.fn();

  const props = {
    configs,
    dispatch
  }
  const checkbox = shallow(
    <CheckBox
      {...props}
    />
  )
  checkbox.find('input').simulate('click')
  expect(dispatch).toHaveBeenCalledWith(update(data))
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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