【问题标题】:Writing Mocha Test for Async functions which uses setTimeout()为使用 setTimeout() 的异步函数编写 Mocha 测试
【发布时间】:2017-02-26 08:08:05
【问题描述】:

不知何故,我无法为一个相对非常简单的功能编写 Mocha JS 测试。 JavaScript 源文件如下所示

exports.cb = function() {
    console.log("The function is called after 3 seconds");
}

exports.testfn = function(cb) {
  setTimeout(cb, 3000);
}

而测试代码写成

describe('Main Test', function(){
  it('A callback Tests', function(done){
    asn.testfn(asn.cb);
    done();
  });
});

我遇到了 2 个问题。

    1. 测试代码立即以 done() 结束
    1. 如果我不调用 done(),则调用该函数但测试失败,因为它希望为异步函数调用 done()

我查看了文档,但不确定如何做到这一点。

我可以使用 Promise 编写测试,而且效果很好。但是对于我们需要使用setTimeout的场景,应该怎么做呢?

【问题讨论】:

  • 你想测试什么? testfncb?

标签: javascript node.js mocha.js gulp-mocha


【解决方案1】:

假设你要测试的是testfn,你不会使用cb,你会在测试中使用回调;见 cmets:

describe('Main Test', function(){
  it('testfn calls the function after three seconds', function(done){
    // Remember the start time
    var start = Date.now();
    // Schedule callback
    asn.testfn(function() {
        // Has it been at least three seconds?
        if (Date.now() - start < 3000) {
            // No, trigger an error
        } else {
            // Yes, all's good!
            done();
        }
    });
  });
});

如果你出于某种原因想调用asn.cb,你可以在上面的匿名函数中进行,但如果你想测试asn.cb,你应该在测试asn.testfn之后单独进行。

【讨论】:

    【解决方案2】:
    describe('Main Test', function(){
      it('A callback Tests', function(done){
        asn.testfn(function() {
            asn.cb();
            done();
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-22
      • 2014-02-08
      • 2018-10-02
      • 1970-01-01
      • 2018-08-26
      • 2019-07-09
      • 2015-04-04
      • 1970-01-01
      相关资源
      最近更新 更多