【发布时间】:2018-10-03 22:22:20
【问题描述】:
我的 Angular 5 控制器中有以下功能,我想在其上使用 karma 进行单元测试。
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();
});
从生成的报告中,错误部分没有被覆盖。我错过了什么?
【问题讨论】:
标签: angular unit-testing typescript karma-jasmine karma-coverage