Enzyme test issues returns undefined

alonfai Source

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

javascriptunit-testingreactjsenzyme

Answers

answered 2 years ago Shota #1

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

comments powered by Disqus