使用QUinit的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 thrown@ 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)
怎么办?
答案 0 :(得分:3)
您传递给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'
);
})
&#13;
<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>
&#13;
您可能希望研究使用可能会遇到此问题的linting工具以及其他问题(例如,您有一个缺少分号的 lot ,这可能会导致{{3 }})。