How to use and handle subscribed response from service in unit testing angular 5 to achieve code coverage?

Issue

I am unable to do code coverage of below piece of code. I am using jasmine and karma for code coverage. Angular 5 project.

// demo.component.ts

public demoMethod(): void {
this.myService.getStatus(this.arg1).subscribe((response) => {

this.isLogin = response.isLogin;
if (response.status === 'Status_01') {
this.userStatus = 'Status_01';
} else if (response.status === 'Status_02') {
this.userStatus = 'Status_02';
} else {
this.error = 'Invalid'
}

});
}

// demo.component.spec.ts

describe('demoMethod', () => {
it('should call demoMethod method if', () => {
const response = { status: 'Status_01', isLogin: true };
const 
myServiceSpy = spyOn(component['myService'],'getStatus').and.returnValue(of({ 
response }));
component.demoMethod();
expect(myServiceSpy).toHaveBeenCalled();
});

it('should call demoMethod method else if', () => {
const response = { status: 'Status_02', isLogin: true };
const 
myServiceSpy = spyOn(component['myService'],'getStatus').and.returnValue(of({ 
response }));
component.demoMethod();
expect(myServiceSpy).toHaveBeenCalled();
});
});

I am unable to do code coverage or write unit test cases for if else ladder after the success response.
I am using > ng test --code-coverage --watch=true to see code coverage of demo component.

Solution

I have resolved above issue as below. I try to add response object in of of rxjs; which was causing me issue to handle if-else ladder. You can see where I have added status in below code snippet and it is working for code coverage.

it('should call demoMethod method if', () => {
 const myServiceSpy = spyOn(component['myService'],'getStatus').and.returnValue(of({ 
 status: 'Status_01' 
 }));
 component.demoMethod();
 expect(myServiceSpy).toHaveBeenCalled();
 });

Answered By – Abhijeet Giram

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.