[英]Testing errors in Angular 5 Unit Testing after subscribtion
I have the following function in my Angular 5 controller on which i want to do UnitTesting using karma. 我的Angular 5控制器中具有以下功能,我想在该控制器上使用业力进行单元测试。
this.search.getFirstSearch().subscribe(data => {
this.processSchool = data.search3,
error =><any> this.errorMessage,
()=>{
if(this.errorMessage ===''){
console.log('abc')
}else{
console.log('xxxx')
}
}
});
Unfortunately, I have difficulties testing the function error statement. 不幸的是,我在测试函数错误语句时遇到困难。 I tried the following codes, but as far as I see from generated covrage, this part is not covered.
我尝试了以下代码,但是据我所产生的变化,本部分没有涉及。
it('should simulate error 1 ', () => {
fixture.detectChanges();
const searchService = fixture.debugElement.injector.get(SearchService);
const mockCall= spyOn(searchService, 'getFirstSearch').and.returnValue(Observable.throw({status: 404}));
//call method
comp.processData();
});
it('should simulate error 2 ', () => {
const searchService = fixture.debugElement.injector.get(SearchService);
const mockCall= spyOn(searchService, 'getFirstSearch').and.returnValue(Observable.throw({message: ""}));
//call method
comp.processData();
});
it('should simulate error 3 ', async(() => { fixture.detectChanges();
const searchService = fixture.debugElement.injector.get(SearchService);
let error404 = {status: 404};
backend.connections.subscribe((connection: MockConnection) => {
connection.mockError(error404 as any as Error);
});
comp.processData();
}));
////added test
it('should simulate error 4 ', () => { fixture.detectChanges();
const searchService = fixture.debugElement.injector.get(SearchService);
const mockCall= spyOn(searchService, 'getFirstSearch').and.returnValue(
new ErrorObservable('TwainService test failure'))
comp.processData();
});
it('should simulate error 5', () => { fixture.detectChanges();
const searchService = fixture.debugElement.injector.get(SearchService);
const mockCall= spyOn(searchService, 'getFirstSearch').and.returnValue(Observable.throw({message: ""}));
comp.processData();
});
From the generated report, the error part is not covered. 从生成的报告中,未涵盖错误部分。 What am I missing?
我想念什么?
Based on what you have, I think that you might have extraneous curly braces wrapping the parameters passed to the subscribe method. 根据您所拥有的内容,我认为您可能会有多余的花括号来包装传递给订阅方法的参数。 The subscribe signature is
.subscribe([onNext], [onError], [onCompleted])
. 订阅签名为
.subscribe([onNext], [onError], [onCompleted])
。 Otherwise you have set up methods that are assigned to no variable and will never run (thus why it is saying that the code is never ran). 否则,您将设置没有分配给变量且永远不会运行的方法(因此,为什么说代码永远不会运行)。
this.search.getFirstSearch().subscribe(
data => this.processSchool = data.search3, // onNext
error => this.errorMessage = error, // onError
() => { // onCompleted
if(this.errorMessage === '') {
console.log('abc')
} else {
console.log('xxxx')
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.