2017-08-01 7 views
2

我々次の作業のテスト例があります。第二の試験は、あなたが例外をスローする関数がfunction_name.should.throw(エラー)で渡されないのはなぜですか?

it("should throw when not passed numbers", function() { 
     multiply(2, "4").should.throw(Error); 
    }); 
のようにそれを実行するとハック

(function() { 
     multiply(2, "4"); 
    }).should.throw(Error); 

で実行する必要があります理由について何の説明はありません

"use strict"; 

var should = require("chai").should(); 

var multiply = function(x, y) { 
    if (typeof x !== "number" || typeof y !== "number") { 
    throw new Error("x or y is not a number."); 
    } 
    else return x * y; 
}; 

describe("Multiply", function() { 
    it("should multiply properly when passed numbers", function() { 
    multiply(2, 4).should.equal(8); 
    }); 

    it("should throw when not passed numbers", function() { 
    (function() { 
     multiply(2, "4"); 
    }).should.throw(Error); 
    }); 
}); 

テストが失敗します。

Multiply 
    ✓ should multiply properly when passed numbers 
    1) should throw when not passed numbers 

しかし、通常のノードのスクリプトが失敗しないよう機能を実行している:

Error: x or y is not a number. 
    at multiply (/path/test/test.js:7:11) 

shouldは、それがエラーをスローしているという事実をピックアップしない理由だから私は得ることはありません。

これを匿名でラップする必要がある理由は何ですか?function() { }コール?非同期で実行するか、スコープか何かをテストするのですか?ありがとうございます

答えて

2

チャイは定期的なJavaScriptですが、魔法ではありません。式a().b.c()aのスローがある場合、c()はそれをキャッチできません。 cは実行できません。エンジンcであることも分かりません。aは、.b.cが参照できる値を返さなかったためです。代わりにエラーを投げた。関数を使用すると、参照するオブジェクトが.shouldになります。オブジェクトは検索し、.throwを呼び出します。

それははそれを行うことができない理由だが、ビューのAPIの観点から、何も悪いことはありません:.should.throwだけの機能上のアサーションの代わりに、関数呼び出しです。

チャイのexpectを使用することをお勧めします。これはObject.prototypeには挿入されず、魔法のように見えます。

関連する問題