I am facing an issue in writing test case on component method.
How to test a Angular component method if else block inside subscribe((res) => { ///block} and ToasterService inside it.
I have called the Angular service method in my component.ts file.
within the service call subscribe(response=>{}.
I have validated the response value in if else block, and show toaster message according to result but my karma report says: response=> function not covered and inside if else block not statement not covered.
component.ts
constructor(private userService: UserService,
private toastr: ToastrService) { }
sortUsers(sortKey: string) {
this.userService.getSortUserList(sortKey).subscribe((res) => {
if(res.Success){
this.userService.users = res.Data as User[];
}else{
this.toastr.error(res.Message);
}
});
}
component.spec.ts
it('call sortUser when users are sorted', () => {
const users: User[] = [{
User_Id: 1,
First_Name: 'Madhu Ranjan',
Last_Name: 'Vannia Rajan',
Employee_Id: 12345,
Project_Id: 1,
Task_Id:1,
_id: 'xcv'
}];
component.sortUsers('First_Name');
const res = {Success: true, Data: users}
spyOn(service, 'getSortUserList').and.returnValue(of({Success: true, Data: users}));
});
expecting the below block also to be tested by jasmine:
subscribe((res) => {
if(res.Success){
this.userService.users = res.Data as User[];
}else{
this.toastr.error(res.Message);
}
});
karma report: