where to delete database and close connection after all tests using mocha
You can define a "root" after()
hook before the 1st describe()
to handle cleanup:
after(function (done) { db.connection.db.dropDatabase(function () { db.connection.close(function () { done(); }); });});describe('User', ...);
Though, the error you're getting may be from the 3 asynchronous hooks that aren't informing Mocha to continue. These need to either call done()
or skip the argument so they can be treated as synchronous:
describe('User', function(){ beforeEach(function(done){ // arg = asynchronous done(); }); after(function(done){ done() }); describe('#save()', function(){ beforeEach(function(){ // no arg = synchronous }); // ... });});
By adding a callback (usually named
done
) toit()
Mocha will know that it should wait for completion.
I implemented it a bit different.
- I removed all documents in the "before" hook - found it a lot faster than dropDatabase().
I used Promise.all() to make sure all documents were removed before exiting the hook.
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(); }});