Reputation: 4111
I have a service as follows:
createProdCategory( prodcategory: IProdCategory ) {
console.log(prodcategory);
return this.http.post( this.url, prodcategory )
.map( ( response: Response ) => response.json( ) )
.catch( this.handleError );
}
...
handleError( error: any ) {
console.error( error );
return Observable.throw( error.json( ).error || 'Service error' );
}
I would like to test the path through the handleError function, by way of the RXJS catch. My spec is as follows:
it( 'should handle an error on create...', async(() => {
let mockData: ProdCategory = mockDatum[ 2 ];
backend.connections.subscribe((connection) => {
let response: Response = new Response(
new ResponseOptions( { body: JSON.stringify( { error: `${errMsg}` } ), status: 404, statusText: `${errMsg}` } ));
connection.mockRespond( response );
});
expect(
sut.createProdCategory( mockData ).subscribe((resp) => {
fail( 'handleError: expected error...' );
} )
).toThrowError( errMsg );
}));
Unfortunately, the catch is not invoked and the error message is not thrown. How-to force the response to go through the catch.
Upvotes: 1
Views: 651
Reputation: 17879
You need to simulate an error in response.
So instead of
connection.mockRespond( response );
use
connection.mockError(response);
and after that in subscribe you have to handle the error case:
sut.createProdCategory( mockData ).subscribe(
() => {},
error => {
expect(error)......
}
);
Upvotes: 1