Can't seem to catch error when using Jasmine toThrowError

旧街凉风 提交于 2019-12-25 04:04:39

问题


I beginning to try jasmine and I want to use the toThrowError() function but my test does not want to succeed.

I have one function where I throw an error:

test.service.ts

test(list:{}){ 
    if(list == null){
        throw new TypeError();
    }
    else{
        // do something...
    }
}

And my test :

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

And my test fails with an Uncaught TypeError (when I call it I'm doing it in a try catch).


回答1:


You should expect a function, that calls your function with null, to throw an error. Right now you're expecting the result of calling the function to throw an error, which isn't happening.

expect(() => testService.test(null)).toThrowError(TypeError);



回答2:


  • You might have to throw the error from the spy like this here.

  • You were expecting even before throwing the error

    spyOn(foo, "setBar").and.throwError("quux");
    


来源:https://stackoverflow.com/questions/40727581/cant-seem-to-catch-error-when-using-jasmine-tothrowerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!