简体   繁体   English

使用Jasmine测试异步功能的错误处理

[英]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. 因此,基本上,我需要在测试中添加两个额外的catch块才能使此测试正常工作。 Otherwise i get the following error: 否则我得到以下错误:

ERROR: 'Unhandled promise rejection', 'error'

Is there a better way to do this? 有一个更好的方法吗?

So it turns out the issue is simply how karma handles errors for async functions. 因此事实证明,问题仅在于业力如何处理异步功能的错误。 this.uiFeedback was undefined in the $onInit function. this.uiFeedback是在未定义$onInit功能。 However karma did not show the uiFeedback is undefined error until i ran the tests in Chrome and checked the console there. 但是,直到我在Chrome中运行测试并检查那里的控制台后,业力才显示uiFeedback是未定义的错误。 Something for everyone to watch out for when testing async functions with karma jasmine. 在使用业力茉莉花测试async功能时,每个人都需要注意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM