Mongoose与Supertest打开连接问题

我无法运行多个Supertest / Mochatesting,因为我得到一个错误Error: Trying to open unclosed connection. – 我发现这个post提出循环和检查连接状态。 想知道是否有更好的方法? 也许是最近Supertestjoin来处理这个问题的东西。

在你的摩卡testing中,添加一个before函数来连接MongoDB

 var mongoose = require('mongoose'); describe('My test', function() { before(function(done) { if (mongoose.connection.db) return done(); mongoose.connect('mongodb://localhost/puan_test', done); }); }); 

好的 – 非常接近。 我所要做的就是删除describe方法调用,并将一个before()调用放在一个通用文件中,以便进行所有的testing – 超类或者直接摩卡unit testing。

 var db; // Once before all tests - Supertest will have a connection from the app already while others may not before(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 test beforeEach(function (done) { fixtures.load(data, db, function(err) { if (err) throw (err); done(); }) }); 

通过省略describe()调用上面它使它可用于所有testing。

 // 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(); }); });