Javascript 酶测试问题返回未定义
我试图使用{mount}方法对我的React类组件进行单元测试。当我尝试访问类变量(使用这个关键字)时,运行测试会给出一个未定义的错误。下面的示例中,this.DataSource在调用Javascript 酶测试问题返回未定义,javascript,unit-testing,reactjs,enzyme,Javascript,Unit Testing,Reactjs,Enzyme,我试图使用{mount}方法对我的React类组件进行单元测试。当我尝试访问类变量(使用这个关键字)时,运行测试会给出一个未定义的错误。下面的示例中,this.DataSource在调用mount( 导出类GridComponent扩展React.Component{ 建造师(道具){ 超级(道具) 此.state={ 页面记录:[], 总数:0 } 此选项={ 页码:1, 规模:10 } this.DataSource=[]//所有记录都将存储在此处 } componentDidMount()
mount(
导出类GridComponent扩展React.Component{
建造师(道具){
超级(道具)
此.state={
页面记录:[],
总数:0
}
此选项={
页码:1,
规模:10
}
this.DataSource=[]//所有记录都将存储在此处
}
componentDidMount(){
this.DataSource=this.props.recordArr
this.parseProps()
}
组件将接收道具(下一步){
this.DataSource=nextrops.recordArr
this.parseProps()
}
parseProps=()=>{
让pageRecords=[]
如果(!\u.isEmpty(this.DataSource)){//this.DataSource==>未定义
让startIndex=(this.options.page-1)*this.options.sizePage
让计数=(this.options.page-1)*this.options.sizePerPage+this.options.sizePerPage
pageRecords=\ u0.slice(this.DataSource,startIndex,count)
}
这是我的国家({
…这个州,
pageRecords:pageRecords,
totalSize:this.DataSource.length
})
}
render(){
…//呈现来自this.state.pageRecords的记录
}
}
将
this.DataSource
更改为组件状态,然后在测试用例中使用
wrapper.setState({ DataSource: 'somesource' });
例如,组件的componentWillReceiveProps方法如下所示:
componentWillReceiveProps(nextProps) {
this.setState({
DataSource: nextProps.recordArr,
});
this.parseProps()
}
使用箭头函数表达式有什么原因吗?可能是匿名箭头函数表达式中包含了
this
。请使用调试器检查this
。尝试直接引用recordArr prop而不是DataSource私有变量。我可以将DataSource存储在状态中。但是,这被视为n React中的反模式,因为建议将只需要作为呈现方法一部分的数据存储在状态中,或者更改后将重新呈现组件(请参阅)。此外,this.DataSource是calc pageRecords的帮助对象,这是我在呈现组件时使用的对象(在本例中,我使用的是React引导表网格库)。因此,拥有这种内部状态是可能的,但如果可能的话,最好避免这种情况,在这种情况下,为什么不从数据源计算pageRecords,然后将其设置为您的状态?实际上,当pageRecords更改时,重新呈现组件是您想要的(您也可以尝试在构造函数中执行此操作)
componentWillReceiveProps(nextProps) {
this.setState({
DataSource: nextProps.recordArr,
});
this.parseProps()
}