I am writing a unit test for subscribe call but I am not able to cover the error handling part of the subscribe method. In case of 403 error there is a handleError funtion which handles error for statusCode=403 and other statusCodes. Any help will be highly appreciated!
component.ts file
getData(){
this.someService.getResponse().subscribe(res=>{
this.showForm=true;
this.Form.patchValue({
flag:res && res.someflag? "true" : "false"
})
},((error: HttpErrorResponse) => {
this.handleError(error);
}));
}
handleError() function in component.ts file
handleError(error){
this.showForm=false;
if(error.error && error.error.statusCode === 403){
this.itemError=false;
this.overlayError=true;
}
else{
this.itemError=true;
this.overlayError=false;
}
}
component.spec.ts file
This is what I tried but it is not covering the test case.
it('should handle error for 403',async()=>{
const param={statusCode:403};
const errorResponse=new Error('403 errror');
spyOn(component["someService"],"getResponse").and.returnValue(throwError(errorResponse));
component.handleStatusCodeError(param);
expect(component.showForm).toBe(false);
expect(component.itemError).toBe(false);
expect(component.overlayError).toBe(true);
})
CodePudding user response:
Instead of
const errorResponse = new Error('403 error');
you should mock the response as following
const errorResponse = new HttpErrorResponse({ status: 403, error: {}});