简体   繁体   中英

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

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.

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();
 });

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM