asulaiman
asulaiman

Reputation: 1271

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?

Upvotes: 1

Views: 797

Answers (1)

asulaiman
asulaiman

Reputation: 1271

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.

Upvotes: 2

Related Questions