2012-12-15 97 views
4

我得到了我的摩卡测试以下错误,当猫鼬试图连接到MongoDB中:摩卡猫鼬错误

Error: Trying to open unclosed connection. 

这里是我的测试:

var cfg = require('../config') 
, mongoose = require('mongoose') 
, db = mongoose.connect(cfg.mongo.uri, cfg.mongo.db) 
, User = require('../models/user') 
, Item = require('../models/item') 
, should = require('should') 
, fakeUser 
, fakeItem; 

mongoose.connection.on('error', function(err){ 
    console.log(err); 
}); 

describe('User', function(){ 
    beforeEach(function(done){ 
     //clear out db 
     User.remove(done); 

    }); 

    after(function(done){ 
     //clear out db 
     User.remove(function(err){ 
      Item.remove(done); 
     }); 
    }); 

}); 

回答

7

关闭连接完成后:

after(function(done){ 
    //clear out db 
    User.remove(function(err){ 
     Item.remove(function() { 
      mongoose.connection.close(); 
      done(); 
     });   
    }); 
}); 
+0

我认为这通常会工作,但我有更多的测试,而不仅仅是这一个,所以不知道在哪里把.after()。 – chovy

+0

将所有测试包装在一个没有测试的'describe()'中,只包含'after()'块(以及其余的'describe()'块),在其中放置你的'close()'函数。 – glortho