1

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

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

如果我不将 submit.save 的主体包装在 try/catch 中,Jasmine 将通过以下测试

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 来运行我的测试。

4

1 回答 1

1

You will test that your function will throw an error. To do so you can't set the block that will throw an error into a try catch/block cause then no error is thrown in this function even if it was thrown in a function your function calls.

What jasmine does is to catch the error in the toThrow matcher and the test will only pass when the catch block in the matcher was called:

    try {
      actual();
    } catch (e) {
      threw = true;
      thrown = e;
    }
于 2013-06-09T16:51:30.503 回答