如何断言函数不会引发异常

ani*_*sen 17 javascript testing unit-testing qunit

QUnit有一个断言用于测试函数引发异常(QUnit/raise).是否可以 - 使用QUnit - 断言函数不会引发异常.

我意识到可以像下面的代码一样测试它:

try {
    theTest();
    ok(true);
} catch (e) {
    ok(false, "Expected to succeed");
}
Run Code Online (Sandbox Code Playgroud)

但我认为使用QUnit应该是可能的.有线索吗?

Sam*_*lle 17

qunit中没有这样的方法

但是,如果您只编写以下更短的代码,您将获得相同的结果并具有额外的好处

theTest();
ok(true, "My function does not crash");
Run Code Online (Sandbox Code Playgroud)

1 /如果测试代码引发异常,qunit会将测试标记为失败.

2 /如果选中"no try/catch"复选框,您将能够调试抛出异常的位置,而try/catch不是这种情况

  • 事实证明,这有点太简单了.如果函数引发异常,则测试失败*没有*失败消息.如果函数未引发异常,则测试按预期成功.ok() - 断言中的消息从未使用过. (3认同)