lundi 27 avril 2020

How to test if error thrown in error handling function in Jasmine

In my Angular application I have a component that subscribes to an observable and in the subscribe method assigns the returning value to a property. Should the request fail, I want to reset the value in the component and pass the error to the global error handler (which we implemented ourselves and takes care of notifying the user).

someFunction(): void {
   const myObservable = this.service.someFunction(); //simplified; in the actual code there are some ifs and elses that determine which function is actually called
   myObservable.subscribe(
        (response) => {
            this.result= response;
        },
        (error => {
            this.result = null;
            throw error;
            }
        ));
}

This piece of code works just fine in the actual application. The only proplem is that I don't understand how to test it properly. I wrote a spy that throws an error so that the error handling function can rethrow it. It looks like this:

spyOn(serviceMock, 'someFunction').and.returnValue(throwError('Error!!'));

Since the error is not thrown in the function directly but rather in the asynchronously executed error handling function, it won't work if I use

expect(component.myFunction()).toThrowError() //test fails because apparently no error is thrown, although I get an 'unhandled exception: Error!!' in the console

Neither can I use a try catch in the test, because then the error will be thrown, but not caught. Yet the test will fail, because the error occured.

I would like to test that the error is rethrown or at least like my test not to fail, because this error is thrown.

Can you please tell me if that is possible in Jasmine or if this idea of throwing errors and using the global error handler isn't such a good idea after all?

Any help would be appreciated :)

Aucun commentaire:

Enregistrer un commentaire