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.