我必须为PlayerList
容器和Player
组件编写单元测试用例。为分支和props编写测试用例是可以的,但是我如何测试组件的方法和其中的逻辑。我的代码覆盖率不完整,因为这些方法没有经过测试。
设想:
父组件将对其方法的引用onSelect
作为对子组件的回调传递。该方法在PlayerList
组件中定义,但Player
会生成调用它的 onClick 事件。
父组件/容器:
import React, { Component } from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {selectTab} from '../actions/index';
import Player from './Player';
class PlayerList extends Component {
constructor(props){
super(props);
}
onSelect(i) {
if (!i) {
this.props.selectPlayer(1);
}
else {
this.props.selectPlayer(i);
}
}
createListItems(){
return this.props.playerList.map((item, i)=>{
return (
<Player key={i} tab={item} onSelect={() => this.onSelect(item.id)} />
)
});
}
render() {
return(
<div className="col-md-12">
<ul className="nav nav-tabs">
{this.createListItems()}
</ul>
</div>
)
}
}
function mapStateToProps(state){
return {
playerList: state.playerList
}
}
function matchDispatchToProps(dispatch){
return bindActionCreators({selectPlayer: selectPlayer}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(PlayerList);
子组件:
import React, { Component } from 'react';
class Player extends Component {
constructor(props){
super(props);
}
render() {
return(
<li className={this.props.player.selected?'active':''}>
<a href="#" onClick={() => this.props.onSelect(this.props.player.id)}>
<img src={this.props.player.imgUrl} className="thumbnail"/>
{this.props.player.name}
</a>
</li>
)
}
}
export default Player;