[英]Testing errors in Angular 5 Unit Testing after subscribtion
我的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')
}
}
});
不幸的是,我在测试函数错误语句时遇到困难。 我尝试了以下代码,但是据我所产生的变化,本部分没有涉及。
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();
});
从生成的报告中,未涵盖错误部分。 我想念什么?
根据您所拥有的内容,我认为您可能会有多余的花括号来包装传递给订阅方法的参数。 订阅签名为.subscribe([onNext], [onError], [onCompleted])
。 否则,您将设置没有分配给变量且永远不会运行的方法(因此,为什么说代码永远不会运行)。
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.