You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中用Jest测试ngOnInit时出现subscribe未定义错误

Angular组件Jest单元测试报错:TypeError: Cannot read property 'subscribe' of undefined

问题场景

我在用Jest对Angular组件做单元测试时,遇到如下错误:

TypeError: Cannot read property 'subscribe' of undefined

待测试的是组件的ngOnInit生命周期方法,代码如下:

ngOnInit(): void {
    this.editable.subscribe((data) => {
        this.enableEdition = data.enabled;
    });
}

我的测试代码如下:

it('ngOnInit', () => {
    const editableMock = of({ enabled: false });
    component.editable = editableMock;
    component.ngOnInit();
    expect(component.enableEdition).toBe(false);
});

问题推测

我怀疑问题出在editable Observable的组件间传递方式,以及它首次发射值的setTimeout异步逻辑上:

  • editable的源Subject位于table组件(与table-action组件为同级),通过父组件传递:
    父组件模板:

    <table-actions
        [editable]="_editableState">
      </table-actions>
    
      <table>
      </table>
    
  • 父组件通过ViewChild获取table组件的Subject,转为Observable后传给table-action:

    @ViewChild('table', { static: true })
    murTable!: MurTableComponent;
    
    public _editableState!: Observable<any>;
    
    this._editableState = this.murTable.stateEditing.asObservable();
    
  • table组件中Subject的首次发射值在setTimeout内执行:

    ngOnInit(): void {
    
      setTimeout(() => {
        this.onFirstDataRendered(null);
        this.stateEditing.next({ enabled: !!this.editType });
      }, 1500);
    }
    

内容的提问来源于stack exchange,提问作者Jmainol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:10:24