我一直在尝试单元测试一个反应组件,它接受用户输入。更具体地说,我试图在反应组件中测试onChange
函数。然而,我似乎无法设置输入值,我尝试了在互联网上建议的几种不同的方式,但似乎没有任何工作。下面是我试图测试的组件。反应,如何模拟单元测试的用户输入?
class Input extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
/* Check if max length has been set. If max length has been
set make sure the user input is less than max Length, otherwise
return before updating the text string. */
if(this.props.maxLength) {
if(event.target.value.length > this.props.maxLength) {
return;
}
}
this.setState({ value: event.target.value });
}
render() {
const { disabled, label, maxLength, multiline, type, value, ...others} = this.props;
const theme = themeable(others.theme);
let inputClassName = classNames({
"input": type !== 'checkbox',
"checkbox": type == 'checkbox',
disabled,
multiline,
value,
[`${this.props.className}`]: !!this.props.className
});
return (
<div {...theme(1, 'container')}>
{this.props.label ? <label htmlFor={this.props.htmlFor} {...theme(2, 'label')}>{label}</label> : null}
<input value={this.state.value} {...theme(3, ...inputClassName)} onChange={this.handleChange} type={type} />
</div>
);
}
}
我发现这个问题:https://github.com/airbnb/enzyme/issues/76,并试图向底部的建议,我不断收到未定义或空字符串。我尝试了levibuzolic使用酶的模拟变化的建议,这可以在下面看到。然而,这只是返回AssertionError: expected '' to equal 'abcdefghij'
it('Make sure inputted text is shorter than max length', function() {
const result = mount(<Input maxLength={10}></Input>);
result.find('input').simulate('change', {target: {value: 'abcdefghijk'}});
expect(result.state().value).to.equal("abcdefghij");
});
然后我试图takkyuuplayer的建议,这也是下面。这也将失败,并AssertionError: expected '' to equal 'abcdefghij'
it('Make sure inputted text is shorter than max length', function() {
const result = mount(<Input maxLength={10}></Input>);
result.find('input').node.value = 'abcdefghijk';
expect(result.state().value).to.equal("abcdefghij");
});
我发现这篇文章:https://medium.com/javascript-inside/testing-in-react-getting-off-the-ground-5f569f3088a#.f4gcjbaak和尝试他们的方式也失败了。
it('Make sure inputted text is shorter than max length', function() {
const result = mount(<Input maxLength={10}></Input>);
let input = result.find('input');
input.get(0).value = 'abcdefghijk';
input.simulate('change');
expect(result.state().value).to.equal("abcdefghij");
});
最后我试图使用由Simulating text entry with reactJs TestUtils所建议的反应测试utils的,下面是我尝试的代码,但是这并没有与错误消息:TypeError: Cannot read property '__reactInternalInstance$z78dboxwwtrznrmuut6wjc3di' of undefined
it('Make sure inputted text is shorter than max length', function() {
const result = mount(<Input maxLength={10}></Input>);
let input = result.find('input');
TestUtils.Simulate.change(input, { target: { value: 'abcdefghijk' } });
expect(result.state().value).to.equal("abcdefghij");
});
那么如何一个模拟用户输入所以他们可以测试onChange
函数?