Mocha如何通过我的异步测试知道等待和超时?

Pau*_*ish 13 mocha.js node.js

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

done每当我的测试是异步的时候,Mocha就可以很好地处理这个问题,允许我指定一个回调.

我的问题是,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;
      });
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

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

小智 20

这是简单纯粹的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;
}
Run Code Online (Sandbox Code Playgroud)

根据您的函数是否使用参数定义,Mocha的逻辑会发生变化.