Created
October 21, 2018 21:43
-
-
Save roblingle/25c88058079c77c520276b92711ea36c to your computer and use it in GitHub Desktop.
Jest: avoid topology-destroyed error by waiting for index creation in `afterAll`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mongoose from 'mongoose'; | |
import MongodbMemoryServer from 'mongodb-memory-server'; | |
let mongoServer; | |
beforeAll(async () => { | |
mongoServer = new MongodbMemoryServer(); | |
const mongoUri = await mongoServer.getConnectionString(); | |
await mongoose.connect( | |
mongoUri, | |
{useNewUrlParser: true}, | |
); | |
}); | |
afterAll(async () => { | |
// via https://stackoverflow.com/a/51455290/2747869 | |
// Wait until indexes are created or you'll frequently get topology-destroyed errors | |
await Promise.all( | |
mongoose.modelNames().map(model => mongoose.model(model).createIndexes()), | |
); | |
await mongoose.disconnect(); | |
mongoServer.stop(); | |
}); | |
export async function resetDatabase() { | |
await mongoose.connection.db.dropDatabase(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment