This seems to be a regularly occurring question and is an important part of unit testing if you want to ensure your controllers are thoroughly tested.
There are a couple of ways of testing failed response functions when calling an api. In this case I’ll be returning a failed Observable, but you can use the same methods for Promises.
The first way to is to mock out the service/provider and return a failed response.
TestBed.configureTestingModule( {
providers: [
{ provide: myProvider, useValue: { myMethod: () => { return Observable.throw( { status: 404 } )} } }
]
} );
The other method is to spy on the service call and return the error.
spyOn( component.myService, 'myMethod' ).and.callFake( () => {
return Observable.throw( { status: 404 } )
});