我应该如何在摩卡unit testing中初始化一个Mongoose连接?

我一直在找这个地方。 有些人似乎这样做

mongoose.connect('mongodb://localhost/test'); 

并继续他们的describe电话。 那asynchronous的等待呢?

 var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function (callback) { // yay! }); 

我应该如何在摩卡testing中使用这个连接? 我应该把所有的testing在callback? 我应该等待连接代码在unit testing? 这个连接是否会持续describe

Mongoose connect函数支持callback。

由于before Mochaasynchronous版本也接受callback(通常称为done ),只需将其传递给connect函数,如:

 describe("Your test", function () { before(function (done) { mongoose.connect('mongodb://localhost/test', done); }); // here you can write your tests }); 

通过这种方式,连接将保持在before方法放置的describe范围内。

但是,如果你想在你的testing文件中使用你的连接进行所有的testing,只需在describe之前调用它:

 before(function (done) { mongoose.connect('mongodb://localhost/test', done); }); describe("first suite", function () { // do your tests }); describe("second suite", function () { // do your tests }); // and so on