在编写 QUnit 测试时,我对“throws”的行为感到惊讶。 关于下面的代码(http://jsfiddle.net/DuYAc/75/),谁能回答我的问题:
function subfunc() {
throw "subfunc error";
}
function func() {
try {
subfunc();
} catch (e) {}
}
test("official cookbook example", function () {
throws(function () {
throw "error";
}, "Must throw error to pass.");
});
test("Would expect this to work", function () {
throws(subfunc(), "Must throw error to pass.");
});
test("Why do I need this encapsulation?", function () {
throws(function(){subfunc()}, "Must throw error to pass.");
});
test("Would expect this to fail, because func does not throw any exception.", function () {
throws(func(), "Must throw error to pass.");
});
只有第二个测试失败了,尽管这是我编写此测试的自然选择...
问题:
1) 为什么我必须使用内联函数来包围我的测试函数?
2) 为什么最后一次测试没有失败? 'func' 不会抛出任何异常。
将不胜感激阅读任何解释。
最佳答案
1) 为什么我必须使用内联函数来包围我的测试函数?
你不知道。当您编写 throws(subfunc(), [...])
时,首先评估 subfunc()
。由于 subfunc()
在 throws
函数之外抛出,测试立即失败。为了修复它,您必须向 throws
传递一个函数。 function(){subfunc()}
有效,但 subfunc
也有效:
test("This works", function () {
throws(subfunc, "Must throw error to pass.");
});
2) 为什么最后一个测试没有失败? 'func' 不会抛出任何异常。
出于同样的原因。 func()
首先被评估。由于没有明确的 return
语句,它返回 undefined
。然后,throws
尝试调用 undefined
。由于 undefined
不可调用,因此抛出异常并通过测试。
test("This doesn't work", function () {
throws(func, "Must throw error to pass.");
});
关于javascript - 了解 QUnit 异常测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21095840/