【问题标题】:NodeUnit - Testing an asynchronous functionNodeUnit - 测试异步函数
【发布时间】:2015-04-25 04:44:14
【问题描述】:

我想用nodeunit 测试异步函数返回的结果。我有以下测试:

module.exports = {
  createFail: function(assert) {
    var user = new CRUDUser({ firstName: 'Node' });

    assert.equal(undefined, user.id);

    user.create(function(res) { // user.create() makes an async AJAX call and should call this function back
      assert.equal(false, res.success);
      assert.equal(undefined, user.id); // user not created cause 'lastName' can't be null

      console.log('#####');
      assert.done();
    });
  }
};

但是当我运行它时,我收到以下错误:

FAILURES: Undone tests (or their setups/teardowns): 
- createFail

To fix this, make sure all tests call test.done()

如果我将 assert.done(); 调用移到回调函数之外,则测试会在 AJAX 调用之前结束。

我还尝试在测试的最开始添加assert.expect(3);,使其“等待”直到回调函数调用assert.done();,但我得到与上面相同的错误。

在所有情况下,预期的##### 显然不会输出到控制台。我做错了什么??

【问题讨论】:

    标签: javascript node.js unit-testing asynchronous nodeunit


    【解决方案1】:

    根据您的输出,我的第一个理论是user.create 根本没有调用回调函数。对此进行调试并确保在所有情况下(成功、失败、超时等),它实际上都会调用回调函数。换句话说,您的测试代码看起来可能没问题,但您正在测试的代码可能存在错误。

    【讨论】:

    • create() 方法实际上是在调用回调但没有任何参数,我相信这会导致assert.equal(false, res.success); 行结束测试。不管怎么说,还是要谢谢你。我接受您的回答,因为您在某种程度上是对的:问题出在 create() 方法中。
    猜你喜欢
    • 1970-01-01
    • 2013-08-02
    • 2014-02-08
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多