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();
});
})
})
})
這是由摩卡通過了一項功能,當它檢測到您傳遞給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!
你指出,我想到了「的地方完成未定義「錯誤。執行它()時,執行任何操作都應該爲時已晚 - 即使如此:Mocha如何確切地爲這個已命名但未定義的參數定義函數? –
@MichaelBorgwardt你爲什麼期望它是未定義的?它是一個函數的參數聲明(一個匿名函數,在那一刻被*傳遞*但不被稱爲*)。請參閱我的編輯以瞭解它()()的實現方式(以簡化形式)。 – robertklep
啊,謝謝你的代碼。這最終迫使我意識到我是一個完全錯誤的軌道。我不習慣簡單嵌套的函數定義... –