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.");
    });

失敗するのは 2 番目のテストだけですが、これはこのテストを作成する際の私の自然な選択でした...

質問:

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 に答える