Reputation: 21585
I would like to drop database after all tests in all files ran. Is there a hook for it in Mocha?
after()
hook can be applied only within 1 file only.
Upvotes: 1
Views: 130
Reputation: 8443
There is a root level hook in mocha. For your case, you can create a new file and specify drop database command in after
function. That's it!
// init-test.js
after(function() {
// drop database
});
You don't need to move any test in other test file for this solution.
Reference: https://mochajs.org/#root-level-hooks
Upvotes: 1
Reputation: 21585
I'm using process.on('exit')
. It works when running only one file as well as when running tests from package.json.
database.mocha-base.js:
db.connect()
process.on('exit', async () => {
console.log('All tests finished. Droping database')
db.dropDatabase(dbName)
db.disconnect()
})
module.exports = {
applyHooks() {
before(async () => {
// truncate tables
})
}
}
I'm including database.mocha-base.js
in all tests that need database access:
const dbMochaBase = require('./path/to/database.mocha-base.js')
describe('Tests', () => {
dbMochaBase.applyHooks()
...
})
Upvotes: 0
Reputation: 22949
Create a parent file that includes/requires all other tests, then use after
within that file:
describe('User', () => {
require('../user/user.spec.js')
})
describe('Post', () => {
require('../post/post.spec.js')
})
describe('Tag', () => {
require('../tag/tag.spec.js')
})
describe('Routes', () => {
require('./routes.spec.js')
})
after(() => {
// drop database
})
Upvotes: 1