0

I'm having trouble in my component spec testing error scenarios from my service class. The service class is mocked using ts-mockito.

Service class:

export class MyService {
   getData(): Observable<any> {
      /* return httpClient.get(...) */
   }
}

I've simplified the logic which isn't working in my component test to this simple replication (in my real test, the component is calling the service not the test code, but this reproduces what I'm experiencing):

it('should return an error response', () => {
  const httpErrorResponse = new HttpErrorResponse({
    error: { msg: 'Not allowed' },
    status: 400,
    statusText: 'Forbidden',
  });
  const mockTestService = mock(MyService);
  when(mockTestService.getData()).thenReturn(of(httpErrorResponse));
  const mockInstance = instance(mockTestService);
  mockInstance.getData().subscribe(
    (success) => console.log('success'),   /* <= this is what I get */
    (err) => console.log('error')          /* <= this is what I want */
  );
});

However the output here is 'success', not 'error'. How do I setup the observable response from the mock to trigger the error condition in the subscription?

I've also tried when(mockTestService.getData()).thenReject(httpErrorResponse) but this then throws an unhandled promise rejection.

  • 1
    Promises and observables are two different things; a promise doesn't have a subscribe method. To create an *observable* that emits an error see e.g. https://rxjs.dev/api/index/function/throwError. Also your service probably *shouldn't* expose an HttpErrorResponse, because then the details of the transport layer end up in the rest of your app. – jonrsharpe Sep 30 '20 at 07:51
  • Thanks @jonrsharpe, just what I was looking for and this resolves my issue. If you make an answer of your comment, I'd be happy to upvote and accept. And good shout on the exposure of the HttpErrorResponse, food for thought. – Chris Knight Sep 30 '20 at 07:58
  • You should see an option to accept the duplicate, whose answers cover throwError – jonrsharpe Sep 30 '20 at 07:59

0 Answers0