2016-09-15 47 views
1

使用QUinit的throw()聲明我想測試是否引發錯誤和錯誤消息。我有以下功能:正確使用QUnit throw()聲明?

/** 
* Error function for Node. 
* @param {String} msg Error message. 
*/ 
function NodeError (msg) { 
    var that = this 

    /** 
    * Attribute for message. 
    * @type {String} 
    */ 
    this.msg = msg 

    /** 
    * Function rendering NodeError as a string. 
    * @return {String} String representation of NodeError. 
    */ 
    this.toString = function() { 
    return that.msg 
    } 
} 

/** 
* Node object. TODO Fill out. 
* @param {String} title Node title. 
* @throws {NodeError} If no title given 
*/ 
function Node (title) { 
    var that = this 

    if (!title) { 
    throw new Error('Error: no title given') 
    } 

    /** 
    * Node title 
    * @type {[type]} 
    */ 
    this.title = title 
} 

而下面QUnit測試:

QUnit.test('new Node w/o title throws error', function (assert) { 
    assert.expect(1) // Expected number of assertions 

    assert.throws(
    function() { new Node() }, 
    function (err) { err.toString() === 'Error: no title given' }, 
    'Error thrown' 
) 
}) 

然而,單元測試失敗給這個:

Error [email protected] 0 ms 
Expected: 
function(a){ 
    [code] 
} 
Result:  
Error("Error: no title given") 
Diff: 
function(a){ 
    [code] 
}Error("Error: no title given") 
Source:  
    at Object.<anonymous> (file:///Users/maasha/install/src/protwiz/test/test_pw_node.js:10:10) 

怎麼辦?

回答

1

您傳遞給assert.throws的第二個函數應該爲return。您目前有一條評估爲布爾值的語句,但結果將被丟棄。功能然後returns implicitly, thus returning undefined

此外,你投擲new Error(...),而不是NodeError。你需要改變它,或者只使用err.message

這裏有一個固定的版本:

function NodeError (msg) { 
 
    var that = this; 
 
    this.msg = msg; 
 
    this.toString = function() { 
 
    return that.msg; 
 
    } 
 
} 
 

 
function Node (title) { 
 
    var that = this; 
 

 
    if (!title) { 
 
    throw new NodeError('Error: no title given'); // <- CHANGED 
 
    } 
 

 
    this.title = title; 
 
} 
 

 

 
QUnit.test('new Node w/o title throws error', function (assert) { 
 
    assert.expect(1); 
 

 
    assert.throws(
 
    function() { new Node(); }, 
 
    function (err) { return err.toString() === 'Error: no title given' }, // <- CHANGED 
 
    'Error thrown' 
 
); 
 
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/qunit/1.16.0/qunit.min.css" rel="stylesheet"/> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/qunit/1.16.0/qunit.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.js"></script> 
 
<div id="qunit"></div>

你可能要考慮使用掉毛的工具,這可能會抓住這個問題,以及其他人(例如你有一個很多缺少分號的,這可能導致unexpected results)。

+0

謝謝,你是親愛的! – maasha