我一直在嘗試單元測試一個反應組件,它接受用戶輸入。更具體地說,我試圖在反應組件中測試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
函數?