正确使用 QUnit throw() 断言?

Correct use of QUnit throw() assertion?

使用 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)

怎么办?

您传递给 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>

您可能想研究使用 linting 工具,它可能会发现这个问题,以及其他问题(例如,您 很多 缺少分号,这可以导致 unexpected results).