Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Last active October 3, 2016 16:58
Show Gist options
  • Save eschwartz/5308334d293fc4290484aa69b446093f to your computer and use it in GitHub Desktop.
Save eschwartz/5308334d293fc4290484aa69b446093f to your computer and use it in GitHub Desktop.
MongoDB Test Hook
const co = require('co');
const portfinder = require('portfinder');
const mongoServer = require('mongodb-prebuilt');
const tmp = require('tmp');
tmp.setGracefulCleanup();
var db, mongoDataTmp;
before(() => co(function*() {
const dsn = process.env.MONGO_DB_DSN || (yield startMongoServer());
db = yield cb => require('mongodb').MongoClient
.connect(dsn, cb);
console.log(`MongoDB is up and running at ${dsn}`);
}));
function startMongoServer() {
return co(function* () {
const dbPort = yield cb => portfinder.getPort(cb);
console.log(`Starting MongoDB server on ${dbPort}...`);
// Create a mongo data dir
mongoDataTmp = yield cb => tmp.dir({ unsafeCleanup: true },
(err, path, cleanup) => cb(err, { path, cleanup })
);
// Start the mongo server
const mongoStatus = mongoServer.start_server({
args: { port: dbPort, dbpath: mongoDataTmp.path },
auto_shutdown: true
}, errorCode => {
// Sometimes mongoServer sends errors here
// (but not successes)
if (errorCode) {
console.error(`mongo exited with ${errorCode}`)
}
});
// mongodb-prebuilt has crappy error handling
if (mongoStatus !== 0) {
throw new Error(`Failed to start mongodb server`);
}
return `mongodb://localhost:${dbPort}/test_db`;
})
}
// Reset DB after each test, so we can start with a clean slate.
afterEach((done) => db.dropDatabase(done));
// Destroy the MongoDB server
after(() => {
try {
// Delete the data dir
mongoDataTmp.cleanup();
}
catch (err) {
// This happens sometimes, but I don't want it to break tests.
console.warn(`Failed to delete temp mongo data dir at ${mongoDataTmp.path}`);
}
mongoServer.shutdown();
});
module.exports = function getDb() {
return db;
}
@eschwartz
Copy link
Author

Mocha hook to spin up a MongoDB server for tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment