当我使用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中完成的事情吗?
这是正确的,具体的例子。查看George的答案,查看函数长度函数的文档。 –