目前,我正在尝试测试我的应用,我正在尝试测试我的组件方法。所以这是我的组件代码:
import React, {Component} from 'react';
import PropTypes from 'prop-types';
//Style
const style = {
box: {
width: '96%',
height:120,
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10,
marginBottom: 10,
display:'flex',
},
votes: {
width: '12%',
height: '100%',
backgroundColor: '#EEE',
display:'block',
textAlign: 'center',
borderTopLeftRadius:5,
borderBottomLeftRadius:5
},
detail: {
width: '88%',
height: '100%',
backgroundColor: '#DDD',
borderTopRightRadius:5,
borderBottomRightRadius:5,
},
image: {
height: '35%',
width: '35%',
},
}
//Component of one topic, contains all the button to upvote and downvote.
export class OneTopic extends Component {
constructor(props) {
super(props);
//bind all the function
this.upvotes = this.upvotes.bind(this);
this.downvotes = this.downvotes.bind(this);
}
//function to upvote, will call the function that passed by Topic table(but from App.jsx)
upvotes() {
this.props.upvote(this.props.title);
}
//funtion to downvote, will call the function that passed by Topic table(but from App.jsx)
downvotes() {
this.props.downvote(this.props.title);
}
render() {
return(
<div style={style.box}>
<div style = {style.votes}>
<img src="img/upvote.png" className="vote" style={style.image} alt="upvote" onClick = {this.upvotes}/>
<div style={{backgroundColor:'#AAA',padding:3, width: 20, height:20, textAlign:'center', margin:'auto', fontSize:20, marginBottom:4}} >
{this.props.vote}
</div>
<img src="img/downvote.png" className="vote" style={style.image} alt="downvote" onClick={this.downvotes}/>
</div>
<div style = {style.detail}>
<h2 className="margin">{this.props.title} </h2><hr className="margin" />
<p className="margin descrip">{this.props.desc} </p>
</div>
</div>
);
}
}
请关注一个upvotes功能。我尝试使用Jest实例测试这个,这是我的测试代码:
it('Child oneTopic is not crashing', () => {
const wrapper = mount(<oneTopic />);
wrapper.instance().upvotes();
});
这是错误消息:
TypeError: wrapper.instance(...).upvotes is not a function
请帮助我,我不喜欢使用快照,因为它看起来很复杂。
答案 0 :(得分:1)
您可以使用模拟方法。
wrapper.find(".vote").first().simulate('click');
如果您希望模拟其他功能,即downVote
wrapper.childAt(0).childAt(0).childAt(0).simulate('click'); // upVote
wrapper.childAt(0).childAt(0).childAt(2).simulate('click'); // downVote
或者另一种方法是为这两个图像提供唯一的ID。您可以将其作为(“#upVote”)或(“#downVote”)而不是(“。vote”)
进行访问