Angular单元测试报错:Cannot read properties of undefined (reading 'subscribe')
解决Angular单元测试中Cannot read properties of undefined (reading 'subscribe')错误
问题根源
组件中lookup$是commonUtility.initializeLookupList()返回的包含多个Observable属性的对象(如lookup$['example']、lookup$['example2']都是Observable),但你当前测试里的mock返回值是of([{}])——这是一个包裹数组的Observable,而非组件期望的对象结构。导致this.lookup$['example']为undefined,调用subscribe时触发错误。
解决方案
修正initializeLookupList的mock返回值,直接返回一个包含对应Observable属性的对象:
修改测试代码中的mock逻辑
找到测试里的这一行:
mockCommonUtilty.initializeLookupList.and.returnValue(of([{}])); //--mock return value--
替换为:
mockCommonUtilty.initializeLookupList.and.returnValue({ example: of([{ id: 1, label: 'Mock Currency' }]), // 模拟example对应的lookup数据 example2: of([{ id: 2, label: 'Mock Plan Type' }]) // 模拟example2对应的lookup数据 });
关键说明
- 组件中
lookup$不是Observable,而是包含Observable属性的普通对象,所以mock不需要用of()包裹整个返回值,直接返回对象即可。 - 每个属性(如
example、example2)需要是Observable类型,用of()包裹模拟的lookup数据,保证组件能正常调用subscribe。
内容的提问来源于stack exchange,提问作者Alen Aju
相关产品推荐
相关产品推荐

