酶测试问题返回undefined

时间:2016-10-18 23:38:36

标签: javascript unit-testing reactjs enzyme

我正在尝试使用{mount}方法对我的React类组件进行单元测试。当我尝试访问类变量(使用此关键字)时,运行测试会给出undefined错误。下面的示例,其中this.DataSource在调用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
      }
    }

1 个答案:

答案 0 :(得分:0)

this.DataSource更改为组件状态,然后在测试用例中使用Enzyme util setState function:

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

例如,组件的componentWillReceiveProps方法如下所示:

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