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)'
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
Most helpful comment
You have to manually pass an event object as the second argument to
.simulateif you want one to be passed to youronClick