javascript - 了解 QUnit 异常测试

标签 javascript exception testing 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.");
    });

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

问题:

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/

相关文章:

javascript - 将对象键作为 javascript 函数参数传递

javascript - 在新选项卡中打开 PDF 数据对象

c++ - 在 C++ 中验证用户输入的整数

testing - 如何在 UFT 的测试中重新安排 Action 的执行?

performance - Jmeter——__UUID() 有多耗内存?

javascript - 我怎样才能得到最后一个的值(value)?

javascript - 如何使用vuejs在每一行显示复选框

python - ConfigObj 选项验证

c# - 从C#中的异常传递错误代码

testing - 如何测试 Stencil.js 状态变化?