我正在尝试使用{mount}方法对我的React类组件进行单元测试。当我尝试访问类变量(使用此关键字)时,运行测试给出未定义的错误。下面的示例在调用mount(<GridComponent recordArr=[1,2,3] />
后this.DataSource的值为undefined
导出类GridComponent扩展了React.Component {
构造函数( Prop ){
super ( Prop )
this.state = {
pageRecords:[],
totalSize:0
}
this.options = {
页数:1
sizePerPage:10
}
this.DataSource = [] //所有记录都将存储在这里
}
componentDidMount(){
this.DataSource = this.props.recordArr
this.parseProps()
}
componentWillReceiveProps(nextProps){
this.DataSource = nextProps.recordArr
this.parseProps()
}
parseProps =()=> {
让pageRecords = []
如果(!_。isEmpty(this.DataSource)){//this.DataSource ==>未定义
让startIndex =(this.options.page-1)* this.options.sizePerPage
让计数=(this.options.page-1)* this.options.sizePerPage + this.options.sizePerPage
pageRecords = _.slice(this.DataSource,startIndex,count)
}
this.setState({
...这个状态
pageRecords:pageRecords,
totalSize:this.DataSource.length
})
}
render(){
... //从this.state.pageRecords呈现记录
}
}
最佳答案
将this.DataSource
更改为组件状态,然后在测试用例中使用Enzyme util setState function:。
wrapper.setState({ DataSource: 'somesource' });
例如,您组件的componentWillReceiveProps方法将如下所示:
componentWillReceiveProps(nextProps) {
this.setState({
DataSource: nextProps.recordArr,
});
this.parseProps()
}
关于javascript - enzyme 测试问题返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119774/