【问题标题】:How does Mocha know to wait and timeout only with my asynchronous tests?Mocha 怎么知道只有我的异步测试才能等待和超时?
【发布时间】:2012-11-14 06:18:01
【问题描述】:

当我使用 Mocha 进行测试时,我经常需要同时运行异步和同步测试。

Mocha 很好地处理了这个问题,允许我在测试异步时指定回调 done

我的问题是,Mocha 如何在内部观察我的测试并知道它应该等待异步活动?只要我在测试函数中定义了回调参数,它似乎就在等待。您可以在下面的示例中看到,第一个测试应该超时,第二个应该在 user.save 调用匿名函数之前继续并完成。

// In an async test that doesn't call done, mocha will timeout.
describe('User', function(){
  describe('#save()', function(){
    it('should save without error', function(done){
      var user = new User('Luna');
      user.save(function(err){
        if (err) throw err;
      });
    })
  })
})

// The same test without done will proceed without timing out.
describe('User', function(){
  describe('#save()', function(){
    it('should save without error', function(){
      var user = new User('Luna');
      user.save(function(err){
        if (err) throw err;
      });
    })
  })
})

这是 node.js 特有的魔法吗?这是可以在任何 Javascript 中完成的事情吗?

【问题讨论】:

    标签: node.js mocha.js


    【解决方案1】:

    您正在寻找的是函数的长度属性,它可以告诉函数期望多少个参数。当您使用 done 定义回调时,它可以异步告知和处理它。

    function it(str, cb){
      if(cb.length > 0)
        //async
      else
        //sync
    }
    

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/Length

    【讨论】:

    • 谢谢,看来这已经完成了here in the mocha source code。还有一个供参考的例子,var fn1 = function() {};assert.equal(fn1.length, 0);var fn2 = function(param) {};assert.equal(fn2.length, 1)
    【解决方案2】:

    这是简单的纯 Javascript 魔法。

    函数实际上是对象,它们具有属性(例如函数定义的参数个数)。

    看看mocha/lib/runnable.js中this.async是怎么设置的

    function Runnable(title, fn) {
      this.title = title;
      this.fn = fn;
      this.async = fn && fn.length;
      this.sync = ! this.async;
      this._timeout = 2000;
      this._slow = 75;
      this.timedOut = false;
    }
    

    Mocha 的逻辑会根据你的函数是否使用参数定义而改变。

    【讨论】:

    • 这是正确的,有确切的例子。查看下面 George 的回答,查看有关 Functions 的长度函数的文档。
    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2013-06-27
    • 2019-12-16
    • 1970-01-01
    • 2021-10-03
    • 2020-02-28
    • 2016-09-04
    相关资源
    最近更新 更多