0

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.

1
  • Anyone has any solution for this. Please let know Commented Jul 31, 2021 at 8:44

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.