【问题标题】:Enzyme test issues returns undefined酶测试问题返回未定义
【发布时间】:2017-02-28 09:47:35
【问题描述】:

我正在尝试使用 {mount} 方法对我的 React 类组件进行单元测试。当我尝试访问类变量(使用 this 关键字)时,运行测试会给出未定义的错误。下面的示例在调用 mount(<GridComponent recordArr=[1,2,3] /> 后 this.DataSource 评估为 undefined

导出类 GridComponent 扩展 React.Component { 构造函数(道具){ 超级(道具) 这个.state = { 页面记录:[], 总大小:0 } this.options = { 页数:1, 每页大小:10 } this.DataSource = [] //所有记录都会存放在这里 } 组件DidMount() { this.DataSource = this.props.recordArr this.parseProps() } 组件WillReceiveProps(nextProps) { this.DataSource = nextProps.recordArr this.parseProps() } parseProps = () => { 让 pageRecords = [] if (!_.isEmpty(this.DataSource)) { //this.DataSource ==> 未定义 让 startIndex = (this.options.page - 1) * this.options.sizePerPage 让 count = (this.options.page - 1) * this.options.sizePerPage + this.options.sizePerPage pageRecords = _.slice(this.DataSource, startIndex, count) } 这个.setState({ ...这个状态, pageRecords:pageRecords, totalSize:this.DataSource.length }) } 使成为() { ... //从this.state.pageRecords渲染记录 } }

【问题讨论】:

  • 您使用箭头函数表达式是否有原因?也许this 包含在您的匿名箭头函数表达式中。使用调试器并检查this。尝试直接引用 recordArr 属性而不是 DataSource 私有变量。

标签: javascript unit-testing reactjs enzyme


【解决方案1】:

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

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

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

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

【讨论】:

  • 我可以将数据源存储在状态中。然而,这在 React 中被认为是一种反模式,因为建议存储在 State 中的数据只需要成为 render 方法的一部分,或者在更改时会再次重新渲染组件(请参阅stackoverflow.com/questions/25207703/…)。跨度>
  • 另外,this.DataSource 是计算 pageRecords 的辅助对象,这是我在渲染组件时使用的对象(在这种情况下,我使用的是 react-bootstrap-table 网格库)。所以有这个内部状态是可能的,但如果可能的话,更愿意避免它
  • 明白了,在这种情况下,为什么不从DataSource计算pageRecords,然后将其设置为您的状态?作为 pageRecords 更改时的重新渲染组件实际上是您想要的(您也可以尝试在构造函数中执行此操作)
猜你喜欢
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 2020-01-17
  • 1970-01-01
  • 2017-06-16
  • 2023-03-24
相关资源
最近更新 更多