提问者:小点点

酶测试问题返回未定义


我正在尝试使用{mount}方法对我的React类组件进行单元测试。当我尝试访问class变量(使用这个关键字)时,运行测试会给出一个未定义的错误。下面的示例,其中调用mount(后,此.DataSource的计算结果为未定义


    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个答案

匿名用户

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

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

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

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