使用 Jasmine toThrowError 时似乎无法捕获错误

Jul*_*eau 1 jasmine typescript angular

我开始尝试 jasmine,我想使用 toThrowError() 函数,但我的测试不想成功。

我有一个函数会抛出错误:

测试.service.ts

test(list:{}){ 
    if(list == null){
        throw new TypeError();
    }
    else{
        // do something...
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试:

it('shall throw an error', inject()
    [
        TestService
    ],
    (
        testService: TestService
    ) => {
        let test = testService.test(null);
        expect(test).toThrowError(TypeError);
    }
);
Run Code Online (Sandbox Code Playgroud)

我的测试因 Uncaught TypeError 失败(当我调用它时,我是在 try catch 中执行的)。

Her*_*key 6

您应该期望一个使用 , 调用您的函数的函数null会抛出错误。现在,您期望调用该函数的结果是抛出错误,但这并没有发生。

expect(() => testService.test(null)).toThrowError(TypeError);
Run Code Online (Sandbox Code Playgroud)

换句话说,测试中的以下行:

let test = testService.test(null);
Run Code Online (Sandbox Code Playgroud)

使用 执行test函数null,抛出TypeError. 因为它不在 之内expect,所以 jasmine 认为它是“未捕获的”。抛出错误后,不会执行任何其他操作。该expect(test).toThrowError(TypeError);线路永远不会被呼叫。

我上面显示的代码将一个函数传递给expect. 当 jasmine 运行该函数时,它将抛出TypeError, 并满足toThrowError(TypeError)条件。