5

在编写 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' 不会抛出任何异常。

将不胜感激阅读任何解释。

4

1 回答 1

7

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.");
});
于 2014-01-13T16:28:26.050 回答