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
相关产品推荐
相关产品推荐

