I'm trying to do unit test my React class component using {mount} method. When I try to access the class variable (using this keyword), running the test gives an error of undefined. Example below where this.DataSource evaluate to undefined after calling mount(<GridComponent recordArr=[1,2,3] />
export class GridComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
pageRecords: [],
totalSize: 0
}
this.options = {
page: 1,
sizePerPage: 10
}
this.DataSource = [] //All records will be stored here
}
componentDidMount() {
this.DataSource = this.props.recordArr
this.parseProps()
}
componentWillReceiveProps(nextProps) {
this.DataSource = nextProps.recordArr
this.parseProps()
}
parseProps = () => {
let pageRecords = []
if (!_.isEmpty(this.DataSource)) { //this.DataSource ==> undefined
let startIndex = (this.options.page - 1) * this.options.sizePerPage
let count = (this.options.page - 1) * this.options.sizePerPage + this.options.sizePerPage
pageRecords = _.slice(this.DataSource, startIndex, count)
}
this.setState({
...this.state,
pageRecords: pageRecords,
totalSize: this.DataSource.length
})
}
render() {
... //Render the records from this.state.pageRecords
}
}
thisis enclosed inside your anonymous arrow function expression. Use a debugger and inspectthis. Try referencing the recordArr prop directly instead of the DataSource private variable. - Jecoms