在编写 QUnit 测试时,我对“抛出”的行为感到惊讶。关于以下代码(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' 不会抛出任何异常。
将不胜感激阅读任何解释。