单元测试:TypeError:无法读取未定义的属性“管道”

Posted

技术标签:

【中文标题】单元测试:TypeError:无法读取未定义的属性“管道”【英文标题】:Unit testing: TypeError: Cannot read property 'pipe' of undefined 【发布时间】:2020-01-17 11:29:11 【问题描述】:

我正在尝试为我的组件中的一个功能编写单元测试,在本示例中,它是“设置”。 'setup' 调用另一个函数,'additionalSetup',它在执行管道(take(1))时订阅存储,并获取第一个发射:

private setup() 
    // ...declares/assigns a few variables in the component
    this.additionalSetup() ;


private additionalSetup() 
    this.store.pipe(take(1)).subscribe(/*logic here, but you get the idea*/);

我的单元测试似乎因错误而失败:

TypeError: 无法读取未定义的属性“管道”

在“设置”单元测试中,我尝试模拟“附加设置”:

component.additionalSetup = jest.fn();

这似乎不起作用。我对开玩笑还很陌生,我还在学习。我将采取什么方法来解决此错误?

【问题讨论】:

this.storeundefined,无论出于何种原因,当您调用该代码时。 【参考方案1】:

您的组件已经创建,所以它已经调用了component.additionalSetup。 为了解决问题,您必须在创建组件之前模拟 additionalSetup

这可以通过Angular Testing Library轻松完成

 const component = await render(MyComponent, 
    componentProperties: 
      additionalSetup : jest.fn(),
    ,
  );

或者你可以实现这个yourself

【讨论】:

以上是关于单元测试:TypeError:无法读取未定义的属性“管道”的主要内容,如果未能解决你的问题,请参考以下文章

反应笑话单元测试用例TypeError:无法读取未定义的属性'then'

渲染中的错误:“TypeError:无法读取未定义的属性'_t'”在使用 Jest 的单元测试中

[karma-server]:TypeError:无法读取未定义的属性“范围”-CI 环境中的 Angular 单元测试

TypeError:无法读取未定义的属性“SHORT”

TypeError:无法使用玩笑读取未定义的属性“原型”

VueComponent.mounted:TypeError:无法读取挂载钩子中未定义的属性“get”