In Jest, beforeAll()
is supposed to run before beforeEach()
.
The problem is that when I use an async callback for beforeAll()
, Jest doesn't wait for the callback to finish before going on to beforeEach()
.
How can I force Jest to wait for an async beforeAll()
callback to finish before proceeding to beforeEach()
?
Minimal reproducible example
tests/myTest.test.js
const connectToMongo = require('../my_async_callback')
// This uses an async callback.
beforeAll(connectToMongo)
// This is entered before the beforeAll block finishes. =,(
beforeEach(() => {
console.log('entered body of beforeEach')
})
test('t1'), () => {
expect(1).toBe(1)
}
test('t2'), () => {
expect(2+2).toBe(4)
}
test('t3'), () => {
expect(3+3+3).toBe(9)
}
my_async_callback.js
const connectToMongo = async () => {
try {
await mongoose.connect(config.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
console.log('Connected to MongoDB')
} catch (err) {
console.log(`Error connecting to MongoDB: ${err.message}`)
}
}
module.exports = connectToMongo
UPDATE: As the accepted answer helpfully points out, Jest actually does wait for beforeAll
to finish first, except in the case of a broken Promise chain or a timeout. So, the premise of my question is false. My connectToMongo
function was timing out, and simply increasing the Jest timeout solved the problem.
catch (err)
is a mistake because it suppresses an error (though this won't prevent beforeAll from proceeding). – DrivewaybeforeAll
andbeforeEach
despite working otherwise. That is, they work when I connect inbeforeEach
(as ugly as that is) or omit Jest altogether. What could explain this behavior, if not Mongoose execution being order-dependent? – Amincatch
, or at least rethrow an error. I'd expect it to work without async..await in beforeAll but I can't confirm this. Any way, for such order you may want custom wrapper over beforeEach, something like,let mongoProm; let beforeEachMongo = async (cb) => { mongoProm = mongoProm || mongoose.connection(...); await mongoProm; return cb() }
. – Driveway