Enzyme: when simulate click, event is undefined in onClick function?

Created on 12 Sep 2016  路  2Comments  路  Source: enzymejs/enzyme

Here is my code:

import React, { Component, PropTypes } from 'react';
import clzName from 'classnames';

const propTypes = {
  layout: PropTypes.oneOf(['vertical', 'horizontal']),
  /**
  * @example
  * data = [{value: 'China', text: '涓浗'}, ...]
  */
  data: PropTypes.array,
  onItemClick: PropTypes.func,
};
const defaultProps = {
  layout: 'horizontal',
  data: [],
};

export default class RadioGroup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.value || null
    };
    this.handleItemClick = this.handleItemClick.bind(this);
  }

  getValue() {
    return this.state.value;
  }

  handleItemClick(e) {
    const target = e.currentTarget;
    const value = target.value;
    this.setState({ value });
    if (this.props.onItemClick) {
      this.props.onItemClick(e);
    }
  }

  render() {
    let items = [];
    this.props.data.forEach((item, idx) => {
      items.push(
        <div className='radio-item' key={idx}>
          <input
            type='radio'
            value={item.value}
            onClick={this.handleItemClick}
            checked={item.value === this.state.value}
          />
          <span>{item.text}</span>
        </div>
      )
    });
    let className = clzName(
      'radio-group',
      this.props.className,
      this.props.layout,
    )
    return (
      <div className={className}>
        {items}
      </div>
    )
  }

}

RadioGroup.propTypes = propTypes;
RadioGroup.defaultProps = defaultProps;

here is my test case:

describe('RadioGroup', () => {
  const wrapper1 = shallow(
      <RadioGroup layout='horizontal' data={[
      {
        value: 'China', text: '涓浗',
      }
    ]} />);

  it('should get correct value after click', () => {
    wrapper1.find('input[value="China"]').simulate('click');
    expect(wrapper1.state('value')).to.equal('涓浗');
  });
});

somehow, an error was threw like 'TypeError: Cannot read property 'currentTarget' of undefined
at RadioGroup.handleItemClick (C:/Users/afei/codes/react-ui-simulate/src/RadioGroup.jsx:33:20)'

invalid question

Most helpful comment

You have to manually pass an event object as the second argument to .simulate if you want one to be passed to your onClick

All 2 comments

You have to manually pass an event object as the second argument to .simulate if you want one to be passed to your onClick

I find this in documention.And thanks @ljharb

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nelsonchen90 picture nelsonchen90  路  3Comments

AdamYahid picture AdamYahid  路  3Comments

thurt picture thurt  路  3Comments

mattkauffman23 picture mattkauffman23  路  3Comments

potapovDim picture potapovDim  路  3Comments