了解QUnit异常测试

use*_*756 5 javascript testing exception qunit throws

在编写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.");
    });
Run Code Online (Sandbox Code Playgroud)

只有第二次测试失败,尽管这是我编写此测试的自然选择......

问题:

1)为什么我必须使用内联函数来包围我测试的函数?

2)为什么最后一次测试没有失败?'func'不会抛出任何异常.

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

fak*_*234 7

1)为什么我必须使用内联函数来包围我测试的函数?

你没有.当你写作时throws(subfunc(), [...]),subfunc()首先评估.当subfunc()抛出throws函数外,测试立即失败.为了解决它,你必须传递throws一个函数.function(){subfunc()}有效,但也是如此subfunc:

test("This works", function () {
    throws(subfunc, "Must throw error to pass.");
});
Run Code Online (Sandbox Code Playgroud)

2)为什么最后一次测试没有失败?'func'不会抛出任何异常.

出于同样的原因.func()首先评估.由于没有明确的return陈述,它会返回undefined.然后,throws试着打电话undefined.由于undefined不可调用,因此抛出异常并且测试通过.

test("This doesn't work", function () {
    throws(func, "Must throw error to pass.");
});
Run Code Online (Sandbox Code Playgroud)