1

在 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();
      });
    })
  })
})

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

4

1 回答 1

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

它是 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();
});

输出:

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!
于 2013-05-28T08:27:17.573 回答