茉莉在Try/Catch中没有捕获错误

Jasmine not catching errors within Try/Catch

本文关键字:错误 Catch Try      更新时间:2023-09-26

我一直在使用Jasmine框架编写一些angularjs测试。我对Jasmine网站上的文档感到困惑

'toThrow'匹配器用于测试函数是否抛出异常

如果我不包装提交正文,

Jasmine将通过以下测试。保存到try/catch

it("should not save to server if user is invalid", function () {
    userServiceMock.user.id = false;
    expect(function () {
      submissionService.save(submission);
    }).toThrow();
   userServiceMock.user.id = 15;
});

我不认为在没有catch子句的情况下抛出错误是好的做法。所以我一定是把这种测试写错了。希望有人能澄清一下。

我使用gruntjs和grunt-karma来运行我的测试

您将测试函数是否会抛出错误。要做到这一点,你不能设置将抛出错误的块到try catch/block中,因为即使在函数调用的函数中抛出错误,也不会在该函数中抛出错误。

jasmine所做的是捕获toThrow匹配器中的错误,只有当匹配器中的catch块被调用时,测试才会通过:

    try {
      actual();
    } catch (e) {
      threw = true;
      thrown = e;
    }