假设我有一个名为testService的服务,其中包含函数getData。我也有将服务注入其中的组件(例如A)。
export class A implements OnInit,OnDestroy{
saveObj;
constructor(public service:testService){
}
ngOnDestroy(){
if(this.saveObj) this.saveObj.unsubscribe();
}
ngOnInit(){
this.saveObj = this.service.getData.subscribe(res => {
this.func(res);
},
err => {
console.log("Error Occured");
this.saveObj.unsubscribe();
});
}
private func(result: any){
// Some code
}
}
现在我正在对此组件进行单元测试。问题是在某些情况下,它会引发错误:
Uncaught TypeError: _this.saveObj.unsubscribe is not a function thrown
spec.ts的代码段:
// testServiceStub is just a mock of testService.
beforeEach(async(()=>{
testServiceStub = jasmine.createSpyObj(['getData']);
TestBed.configureTestingModule({
declarations : [A],
schemas : [NO_ERRORS_SCHEMA],
providers : [
{ provide : testService, useValue: testServiceStub }
]
}).compileComponents();
}))
beforeEach(async(()=>{
fixture = TestBed.createComponent(A);
component = fixture.componentInstance;
}))
it('checks whether error is handled or not',()=>{
spyOn(console,'log');
testServiceStub.getData.and.returnValue(throwError({status:404}));
fixture.detectChanges();
expect(console.log).toHaveBeenCalled(); // shows the TypeError
})
it('checks whether value is handled or not',()=>{
testServiceStub.getData.and.returnValue(of(mockData)); // some mock data
fixture.detectChanges();
expect(component.func).toHaveBeenCalled(); // also shows the TypeError
})
我也将此链接称为unsubscribe is not a function on an observable。但是问题是它在某些情况下也可以使用,并且没有显示错误。
[请帮助我找出原因和可能的情况。
UPD:添加了onDestroy生命周期挂钩
根据@Amit Chigadani的建议
export class A implements OnInit,OnDestroy{
saveObj;
constructor(public service:testService){
}
ngOnDestroy(){
if(this.saveObj)
this.saveObj.unsubscribe();
}
ngOnInit(){
this.saveObj = this.service.getData.subscribe(res => {
this.func(res);
},
err => {
console.log("Error Occured");
});
}
private func(result: any){
// Some code
}
}