【问题标题】:How to fix 'cannot read property subscribe' of undefined during angular unit testing?如何在角度单元测试期间修复未定义的“无法读取属性订阅”?
【发布时间】:2019-01-03 06:31:53
【问题描述】:

Angular6 - 单元测试错误“无法读取未定义的属性‘订阅’”

我正在为具有多个依赖项的角度组件编写单元测试。其中一项依赖服务具有一些属性作为可观察对象。我试图模拟此服务,但在标题中抛出错误,

spec.ts

describe('Component', () => {
let mockService= jasmine.createSpyObj(['property1', 'property2', 'property3']);

beforeEach(async(() => {
    TestBed.configureTestingModule({
declarations: [testComponent],
providers: [
......someOther,
{ provide service, useValue: mockService},
......someOther
]
}).compileComponents();

fixture = TestBed.createComponent(testComponent);
component = fixture.componentInstance;
}));

it('should be created', () => {
expect(component).toBeTruthy();
  });
});

ts 文件有

this.Service.property1.subscribe(() => {})
this.Service.property2.subscribe(() => {})
this.Service.property3.subscribe(() => {})

期望测试用例通过但失败并出现标题中的错误

【问题讨论】:

  • 您创建的模拟服务是否具有与实际相同的密钥?
  • 是的,我不能分享实际的代码,但它与上面类似

标签: angular karma-jasmine


【解决方案1】:

不要以这种方式创建间谍,而是尝试在

中创建间谍

然后

编译组件

这样

let service:Service

.compileComponents().then(()=>{

  spyOn(service:Service, 'any method / property').and.returnValue(Observable.of(MOCKDATA));

)}

希望对你有帮助

【讨论】:

  • 请通过console.log检查它在控制台中打印什么以进行服务
猜你喜欢
  • 2019-08-06
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2018-11-11
  • 2017-06-28
  • 1970-01-01
相关资源
最近更新 更多