摩卡如何知道只有我的asynchronoustesting等待和超时?

当我使用Mocha进行testing时,通常需要运行asynchronous和同步testing的组合。

摩卡处理这个美丽的让我指定一个callback, done ,只要我的testing是asynchronous的。

我的问题是,摩卡如何在内部观察我的testing,并知道它应该等待asynchronous活动? 它似乎随时等待我的testing函数中定义的callback参数。 您可以在下面的示例中看到,第一个testing应该超时,第二个应该继续并在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中完成的东西吗?

这是简单的纯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; } 

摩卡的逻辑根据您的function是否用参数定义而改变。

你正在寻找的是函数的长度属性,它可以告诉一个函数需要多less个参数。 当你定义一个callbackdone它可以告诉和asynchronous处理它。

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

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