I am encountering difficulties in writing a test case for an Angular component method.
How can I effectively test an Angular component method that includes an if else
block within a
subscribe((res) => { ///block}
and also utilizes the ToasterService
inside it?
I have invoked the Angular service method in my component.ts file, where the service call is made using subscribe(response=>{})
.
In order to validate the response value within the if else
block and display a toaster message based on the result, I implemented the necessary logic. However, upon checking the Karma report, it indicates that the response=>
function and the statements within the if else
block are not covered.
Below is a snippet of the component.ts code:
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);
}
});
}
And here is the corresponding component.spec.ts code:
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}));
});
The expectation is that the following block should also be tested by Jasmine:
subscribe((res) => {
if(res.Success){
this.userService.users = res.Data as User[];
}else{
this.toastr.error(res.Message);
}
});
Refer to the karma report linked below for more details: