When you write code against an Observable, you subscribe to the result. In the subscribe method you provide the callbacks to perform when the Observable is called back. That means you can execute different code for success and failure.
In the last post I wrote about how to mock up and test Observable<T> in Jasmine so that you can properly assert on asynchronous callbacks. Testing the error path is similar, but there are a couple of other minor things you have to do:
Import the static throw method for the observable. (Note: you may be tempted to just import all of rxjs, but that isn’t necessarily a good idea.)
import ‘rxjs/add/observable/throw’;
Change your spyOn to return Observable.throw( { } ).
spyOn(myService, ‘myMethod’).and.returnValue(Observable.throw(‘error object’));
Then proceed as normal, wrapping the assertion in fixture.whenStable().then( () => { });
RxJS 6 testing error paths – Darchuk.NET
[…] a previous post I talked about how to use Observable.throw to simulate an Observable error in a unit test. […]