I'm trying to write tests for my Node.js backend application with Jest.
The backend has mongodb implementations via mongoose.
I need to have a global hook, in which I can connect to the database before running all tests in all test files.
In Mocha, I can do it easily as documented here:
You may also pick any file and add “root”-level hooks. For example, add
beforeEach()outside of alldescribe()blocks. This will cause the callback tobeforeEach()to run before any test case, regardless of the file it lives in (this is because Mocha has an implieddescribe()block, called the “root suite”).
So I could, for example, create a testHelper.js file and write:
const mongoose = require('mongoose');
// ./test/testHelper.js
before((done) => {
const mongoURI = `${process.env.DB_MONGO_URI}/testdb`;
mongoose.connect(mongoURI, { useNewUrlParser: true});
mongoose.connection
.once('open', done)
.on('error', (error) => {
console.warn(error);
done();
});
});
after(() => {
mongoose.disconnect();
});
The above will run before and after all tests in all test files.
How can I do the same above with jest?