knbibin
knbibin

Reputation: 1211

Angular Observable error part unit testing using jasmine

I have the below function in my angular service "config.service.ts". I have written some unit test cases for the same and I'm unable to cover the error part of the subscribe method.

getConfiguration(params){
  return new Promise((resolve, reject) => {
    try {
      this.httpService.post('getConfig', params).subscribe{
        data => {
         resolve(data);
        },
        error => {
         reject(error);
        }
      };
    } catch(error) {
     reject(error);
    }
  });
}

Below is the 'config.service.spec.ts' code. Please let me know how to cover the subscribe error part for the same.

it('coverage for getConfiguration()', () => {
 const service: ConfigService = Testbed.get(ConfigService);
 const param = {id: 10};
 const response = {success: true};
 const httpService: HttpService = Testbed.get(HttpService);
 spyOn(httpService, 'post').and.returnValue(of(response));
 service.getConfiguration(param).then(function() {});
 expect(service.getConfiguration).toBeTruthy();
});

Here the observable error part is not covering and unable to reach the coverage. Kindly correct me if anything wrong here.

Upvotes: 0

Views: 7124

Answers (1)

MikeJ
MikeJ

Reputation: 2324

To reach the Observable's error handler, you can use RxJS throwError to force the Observable to throw. So your test could look something like this:

it('rejects when post throws', async () => {
  const param = { id: 10 };
  const errorResponse = new Error('httpService.post error');
  spyOn(httpService, 'post').and.returnValue(throwError(errorResponse));

  await service.getConfiguration(param).catch(err => {
    expect(err).toBe('Subscribe error: httpService.post error');
  });
});

Here's a StackBlitz showing this approach.

Also, regarding the test you posted in your question, if that's your actual test code, you should know that this expect:

expect(service.getConfiguration).toBeTruthy();

will always pass because service.getConfiguration is a function, so it will always evaluate to truthy. You would need to invoke the function if you wanted to verify its behavior in some way.

Also, I believe this line in your posted service code has a syntax error:

this.httpService.post('getConfig', params).subscribe{

It would need an open-parenthesis after .subscribe, before the open curly:

this.httpService.post('getConfig', params).subscribe({

but I'm guessing that's just a copy-paste error constructing your question.

Upvotes: 7

Related Questions