How can i coverage test of submit action with subscribe event? i have this:
onSubmit() {
this.myService.myMethod(value)
.subscribe((result: any) => {
console.log(result);
},
error => {
console.log(error);
},
() => {
console.log('completed);
}
);
}
test
it('should test submit',
inject([myService, XHRBackend], (myService: any, mockBackend: any) => {
const mockResponse = {
error: false,
msg: `Completed`
};
mockBackend.connections.subscribe((connection: any) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(mockResponse)
})));
});
myService.myMethod().subscribe(() => { });
}));
My test coverage show that i haven't tested the subscribe lines.
There are few flaws in the component code of onSubmit. How can you test the outcome when you are just doing console.log etc. You need to handle some kind of flag and show/hide spinner or provide some error/success message. Then you can test the function with error and success. For example:
onSubmit() {
this.showSpinner = true;
this.myService.myMethod(value)
.subscribe((result: any) => {
this.msg = 'success';
},
error => {
this.msg = 'error';
},
() => {
this.showSpinner = false;
}
);
}
in test file:
class MySvcMock{
myMethod() { return of('someVal')}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
provider: [{provide: MyService, useClass: MySvcMock}]
}).compileComponents();
...
...
it('should set success msg on submit',()=>{
component.msg = '';
component.onSubmit();
expect(component.msg).toBe('success');
expect(component.showSpinner).toBeFalsy();
})
it('should set error msg on submit error',()=>{
component.msg = '';
spyOn(component.myService,'myMethod').and.returnValue(throwError('some error msg'));
component.onSubmit();
expect(component.msg).toBe('error');
expect(component.showSpinner).toBeFalsy();
})
You can refer to my series of article which can help you get more familiar with Karma.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With