Skip to content

Instantly share code, notes, and snippets.

@roblingle
Created October 21, 2018 21:43
Show Gist options
  • Save roblingle/25c88058079c77c520276b92711ea36c to your computer and use it in GitHub Desktop.
Save roblingle/25c88058079c77c520276b92711ea36c to your computer and use it in GitHub Desktop.
Jest: avoid topology-destroyed error by waiting for index creation in `afterAll`
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