I have the following function in my Angular 5 controller on which i want to do UnitTesting using karma.
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])
. 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')
}
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.