alonfai
alonfai

Reputation: 51

Enzyme test issues returns undefined

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
      }
    }

Upvotes: 4

Views: 1517

Answers (1)

Shota
Shota

Reputation: 7330

Change this.DataSource as a component state and then use, Enzyme util setState function: in your test case.

wrapper.setState({ DataSource: 'somesource' });

For example your components's componentWillReceiveProps method will look like this:

componentWillReceiveProps(nextProps) {
  this.setState({
    DataSource: nextProps.recordArr,
  });
  this.parseProps()
}

Upvotes: 0

Related Questions