2012-11-26 55 views
10

当我使用Mocha进行测试时,我经常会遇到需要运行的异步和同步测试的组合。摩卡如何知道只用我的异步测试等待和超时?

摩卡处理这个美妙的让我指定一个回调,done,只要我的测试是异步的。

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

回答

18

这是简单的纯JavaScript魔术。

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

看看如何this.async在摩卡/ lib中设置/ runnable.js根据您的功能是否与参数定义

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; 
} 

摩卡的逻辑变化。

+0

这是正确的,具体的例子。查看George的答案,查看函数长度函数的文档。 –

2

你在找什么是函数的长度属性,它可以告诉一个函数需要多少个参数。当您使用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

+1

谢谢,它看起来像这样[在这里摩卡源代码](https://github.com/visionmedia/mocha/blob/master/lib/runnable.js#L43)。 参考的例子'var fn1 = function(){}; assert.equal(fn1.length,0); var fn2 = function(param){}; assert.equal(fn2.length,1)' –