我正在尝试使用{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 } }
答案 0 :(得分:0)
将this.DataSource
更改为组件状态,然后在测试用例中使用Enzyme util setState function:。
wrapper.setState({ DataSource: 'somesource' });
例如,组件的componentWillReceiveProps方法如下所示:
componentWillReceiveProps(nextProps) {
this.setState({
DataSource: nextProps.recordArr,
});
this.parseProps()
}