Mongoose open connection issue with Supertest
In your Mocha tests add a before
function to connect to MongoDB like so
var mongoose = require('mongoose');describe('My test', function() { before(function(done) { if (mongoose.connection.db) return done(); mongoose.connect('mongodb://localhost/puan_test', done); });});
Ok - was pretty close. What I had to do was remove the describe method call and place a before() call in a common file to all tests - supertest or just straight mocha unit tests.
var db;// Once before all tests - Supertest will have a connection from the app already while others may notbefore(function(done) { if (mongoose.connection.db) { db = mongoose.connection; return done(); } db = mongoose.connect(config.db, done);});// and if I wanted to load fixtures before each testbeforeEach(function (done) { fixtures.load(data, db, function(err) { if (err) throw (err); done(); })});
By omitting the describe() call the above it makes it available to all tests.
// Also you can use the 'open' event to call the 'done' callback// inside the 'before' Mocha hook. before((done) => { mongoose.connect('mongodb://localhost/test_db'); mongoose.connection .once('open', () => { done(); }) .on('error', (err) => { console.warn('Problem connecting to mongo: ', error); done(); }); });