asulaiman asulaiman - 1 month ago 11
Javascript Question

Test error handling of async function with jasmine

I have the following async function:

async $onInit() {
try {
this.settings = await this.Service.getSettings(this.companyId);
} catch (error) {
this.uiFeedback.showSystemError('There was an error processing the request.', error);
}
}


I am trying to test if the function displays an error if the async function catches an error. At the moment the only spec which successfully managed to do this was the following:

it('should show error if api call to get availability settings fails', () => {
Company.getSettings = () => {
throw new Error();
};
try {
cmp.$onInit().catch(() => {});
}
catch (error) {
expect(uiFeedback.showSystemError).toHaveBeenCalled();
}

});


So basically i need to add two extra catch blocks within my test to get this test to work. Otherwise i get the following error:

ERROR: 'Unhandled promise rejection', 'error'


Is there a better way to do this?

Answer Source

So it turns out the issue is simply how karma handles errors for async functions. this.uiFeedback was undefined in the $onInit function. However karma did not show the uiFeedback is undefined error until i ran the tests in Chrome and checked the console there. Something for everyone to watch out for when testing async functions with karma jasmine.