我正在构建一个React应用程序,我想测试某些功能,但是,我不确定应该如何测试它。
首先,我使用React
和ReactDOM
版本15.4.2
我有一个代表输入按钮的组件。
class InnovanaInputBox extends React.Component {
constructor(props) {
super(props);
this.state = this.initializeState();
// Bind all the event handlers.
this.onChange = this.onChange.bind(this);
}
initializeState() {
return {
hasValue: false
}
}
onChange(event) {
this.setState(
{
hasValue: event.target.value !== ""
}
);
}
render() {
return (
<div className={"innovana-input-box" +
(typeof(this.props.className) !== typeof(undefined) &&
this.props.className !== "" ? " " + this.props.className: "") +
(this.state.hasValue ? " value" : "")}>
<input type="text" onChange={this.onChange} />
<label>{this.props.label}</label>
</div>
);
}
}
InnovanaInputBox.PropTypes = {
label: React.PropTypes.string.isRequired
}
export default InnovanaInputBox;
因此,当我在组件内的输入框中输入值时,如果输入框确实包含值,则状态hasValue
会更改为true
。
在render方法中,在容器组件上设置了另一个名为value
的类。
现在,我该如何测试这种特定行为?
我有Karma和Mocha设置,我使用react-addons-test-utils
版本15.4.2
。
我已经有一些基本测试来查看组件是否呈现,但测试这看起来有点困难。
我试图使用Simulate
和findReferedDOMComponentWithClass
,但我没有得到它。
关于如何测试它的任何建议?
亲切的注册
答案 0 :(得分:0)
你没有在类上指定引用,所以另一种让元素测试元素是否有类的方法就是这样做。
const input = document.getElementsByClassName('innovana-input-box')[0];
input.classList.contains('value'); // true
现在,如果有多个,您可能要在元素上指定id并使用document.getElementById()
代替。或者在输入中添加ref
并使用
编辑:
如果你想测试组件上的状态值,你可以做这样的事情
const inputBox = TestUtils.renderIntoDocument(<InnovanaInputBox />);
const input = React.findDOMNode(inputBox).querySelector('input');
input.value = 'some updated value';
TestUtils.Simulate.change(input);
inputBox.state.hasValue // true