In Angular application have a controller with following method
onClick(): void {
this.http
.get('some/endpoint')
.subscribe(
(response) => {
const editUrl = this.service.composeUrl(response);
if (!editUrl) {
// want to test this error is thrown, when editUrl is null
throw Error('Cannot construct valid URL');
}
// do something else
},
() => {
// request clean up
}
);
}
I would like to write Jasmine test to verify, that if the editUrl cannot be composed out of response an error will be thrown.
it('when call is successful but editUrl cannot be constructed, then error is thrown', () => {
mockHttp.get = jasmine
.createSpy()
.and.returnValue(of({}));
mockService.composeUrl= jasmine
.createSpy()
.and.returnValue(null);
expect(() => { component.onClick() }).toThrowError();
});
My test fails with:
Error: Expected function to throw an Error.
But I also see in the browser console, that the error was thrown Uncaught Error: Cannot construct valid URL
I think the problem is in that Error is thrown in the next handler of http observable, and that's somehow running out of jasmine context.
I could fix it by extracting anonymous next handler into named function and test directly that function, but I prefer having subscribe with anonymous arrow functions.