在所有使用摩卡的testing之后,在哪里删除数据库并closures连接

我试图找出到哪里放置一个函数来删除数据库,并在所有testing运行后closures连接。

这里是我的嵌套testing:

//db.connection.db.dropDatabase(); //db.connection.close(); describe('User', function(){ beforeEach(function(done){ }); after(function(done){ }); describe('#save()', function(){ beforeEach(function(done){ }); it('should have username property', function(done){ user.save(function(err, user){ done(); }); }); // now try a negative test it('should not save if username is not present', function(done){ user.save(function(err, user){ done(); }); }); }); describe('#find()', function(){ beforeEach(function(done){ user.save(function(err, user){ done(); }); }); it('should find user by email', function(done){ User.findOne({email: fakeUser.email}, function(err, user){ done(); }); }); it('should find user by username', function(done){ User.findOne({username: fakeUser.username}, function(err, user){ done(); }); }); }); }); 

似乎没有任何工作。 我得到错误:2000毫秒的超时

你可以在第一个describe()之前的after() hook after()定义一个“root”来处理清理:

 after(function (done) { db.connection.db.dropDatabase(function () { db.connection.close(function () { done(); }); }); }); describe('User', ...); 

虽然,你得到的错误可能来自3个不通知摩卡继续的asynchronous挂钩。 这些需要或者调用done()或者跳过这个参数,这样他们可以被视为同步的:

 describe('User', function(){ beforeEach(function(done){ // arg = asynchronous done(); }); after(function(done){ done() }); describe('#save()', function(){ beforeEach(function(){ // no arg = synchronous }); // ... }); }); 

从文档 :

通过添加一个callback(通常命名为doneit()摩卡将知道它应该等待完成。

我实施它有点不同。

  1. 我删除了“之前”挂钩中的所有文件 – 发现它比dropDatabase()快很多。
  2. 我使用Promise.all()来确保在退出钩子之前删除所有文档。

     beforeEach(function (done) { function clearDB() { var promises = [ Model1.remove().exec(), Model2.remove().exec(), Model3.remove().exec() ]; Promise.all(promises) .then(function () { done(); }) } if (mongoose.connection.readyState === 0) { mongoose.connect(config.dbUrl, function (err) { if (err) { throw err; } return clearDB(); }); } else { return clearDB(); } });