Mocha中的回调在哪里以及如何定义?

Mic*_*rdt 1 javascript callback mocha.js

在这个Mocha主页上异步代码的代码示例中:

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;
        done();
      });
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

函数在何处以及如何done定义?它在我看来应该有一个语法错误,因为它只是在没有被定义的情况下使用,或者必须有某种"缺失变量"处理程序,但我在Javascript中找不到类似的东西.

rob*_*lep 7

describe('User', function(){
  describe('#save()', function(){
    it('should save without error', function(done){
                                             ^^^^ look, there! ;-)
      var user = new User('Luna');
      user.save(function(err){
        if (err) throw err;
        done();
      });
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

它是Mocha在检测到您传递的回调it()接受参数时传递的函数.

编辑:这是一个非常简单的独立演示实现如何it()实现:

var it = function(message, callback) { 
  console.log('it', message);
  var arity = callback.length; // returns the number of declared arguments
  if (arity === 1)
    callback(function() {      // pass a callback to the callback
      console.log('I am done!');
    });
  else
    callback();
};

it('will be passed a callback function', function(done) { 
  console.log('my test callback 1');
  done();
});

it('will not be passed a callback function', function() { 
  console.log('my test callback 2');
  // no 'done' here.
});

// the name 'done' is only convention
it('will be passed a differently named callback function', function(foo) {
  console.log('my test callback 3');
  foo();
});
Run Code Online (Sandbox Code Playgroud)

输出:

it will be passed a callback function
my test callback 1
I am done!
it will not be passed a callback function
my test callback 2
it will be passed a differently named callback function
my test callback 3
I am done!
Run Code Online (Sandbox Code Playgroud)