【问题标题】:Enzyme test issues returns undefined酶测试问题返回未定义
【发布时间】:2017-02-28 09:47:35
【问题描述】:
我正在尝试使用 {mount} 方法对我的 React 类组件进行单元测试。当我尝试访问类变量(使用 this 关键字)时,运行测试会给出未定义的错误。下面的示例在调用 mount(<GridComponent recordArr=[1,2,3] /> 后 this.DataSource 评估为 undefined
导出类 GridComponent 扩展 React.Component {
构造函数(道具){
超级(道具)
这个.state = {
页面记录:[],
总大小:0
}
this.options = {
页数:1,
每页大小:10
}
this.DataSource = [] //所有记录都会存放在这里
}
组件DidMount() {
this.DataSource = this.props.recordArr
this.parseProps()
}
组件WillReceiveProps(nextProps) {
this.DataSource = nextProps.recordArr
this.parseProps()
}
parseProps = () => {
让 pageRecords = []
if (!_.isEmpty(this.DataSource)) { //
this.DataSource ==> 未定义
让 startIndex = (this.options.page - 1) * this.options.sizePerPage
让 count = (this.options.page - 1) * this.options.sizePerPage + this.options.sizePerPage
pageRecords = _.slice(this.DataSource, startIndex, count)
}
这个.setState({
...这个状态,
pageRecords:pageRecords,
totalSize:this.DataSource.length
})
}
使成为() {
... //从this.state.pageRecords渲染记录
}
}
【问题讨论】:
-
您使用箭头函数表达式是否有原因?也许this 包含在您的匿名箭头函数表达式中。使用调试器并检查this。尝试直接引用 recordArr 属性而不是 DataSource 私有变量。
标签:
javascript
unit-testing
reactjs
enzyme