2012-04-17 110 views
9

我是新手Qunit和單元測試。聲明函數拋出異常與Qunit

我想弄清楚如何測試以下功能。它並沒有做太多的時刻,但我想斷言,如果我將它傳遞不正確的值正在引發的錯誤:

function attrToggle (panel, attr) { 
    'use strict'; 

    if (!panel) { throw new Error('Panel is not defined'); } 
    if (!attr) { throw new Error('Attr is not defined'); } 
    if (typeof panel !== 'string') { throw new Error('Panel is not a string'); } 
    if (typeof attr !== 'string') { throw new Error('Attr is not a string'); } 
    if (arguments.length !== 2) { throw new Error('There should be only two arguments passed to this function')} 

}; 

如何去斷言的時候,如果這些條件的任何被拋出沒有滿足?

我試圖去看看Qunit的'提出'斷言,但認爲我誤解了它。我的解釋是,如果錯誤發生,測試通過。

所以如果我測試過這樣的事情:

test("a test", function() { 
    raises(function() { 
     throw attrToggle([], []); 
    }, attrToggle, "must throw error to pass"); 
}); 

測試應通過,因爲錯誤拋出。

回答

15

幾件事情錯了,工作的例子是在http://jsfiddle.net/Z8QxA/1/

的主要問題是要傳遞錯誤的東西作爲第二個參數來raises()second argument用於驗證是否引發了正確的錯誤,因此它要麼是正則表達式,要麼是錯誤類型的構造函數,要麼是允許您進行自己的驗證的回調函數。

因此,在您的示例中,您傳遞的是attrToggle作爲將引發的錯誤類型。你的代碼實際上拋出一個Error類型,所以檢查實際上失敗了。傳遞Error作爲第二個參數,你想要的工作原理:

test("a test", function() { 
    raises(function() { 
     attrToggle([], []); 
    }, Error, "Must throw error to pass."); 
}); 

其次,你不叫attrToggle()raises()時需要的throw關鍵字。

1

是的,你說得很對。當您測試代碼時,​​預計會引發錯誤。

通常我用我的函數try-catch來捕捉不正確的參數類型。我用raises()來測試throw。如果我把一個不正確的值作爲參數,並且測試不符合raises(),那麼沒有發現一些東西。