Mongoose不会在Mocha中正确删除数据库和closures连接
我有两个简单的testing,但其中一个testing通过,但不是另一个,因为架构再次编译。
OverwriteModelError:编译后无法覆盖
CheckStaging
模型。
这是我的一个testing,因为它正在运行第一。
var mongoose = require('mongoose'), StagingManager = require('../lib/staging_manager'), expect = require('expect.js'); describe('Staging manager', function() { var StagingModel; beforeEach(function(done) { mongoose.connect('mongodb://localhost/BTest'); StagingModel = new StagingManager(mongoose).getStaging(); done(); }); describe('find one', function() { it('should insert to database', function(done) { // Do some test which works fine }); }); afterEach(function (done) { mongoose.connection.db.dropDatabase(function () { mongoose.connection.close(function () { done(); }); }); }); });
这是失败的testing
var StagingUtil = require('../lib/staging_util'), StagingManager = require('../lib/staging_manager'), mongoose = require('mongoose'); describe('Staging Util', function() { var stagingUtil, StagingModel; beforeEach(function(done) { mongoose.connect('mongodb://localhost/DBTest'); StagingModel = new StagingManager(mongoose).getStaging(); stagingUtil = new StagingUtil(StagingModel); done(); }); describe('message contains staging', function() { it('should replace old user with new user', function(done) { // Do some testing }); }); afterEach(function (done) { mongoose.connection.db.dropDatabase(function () { mongoose.connection.close(function () { done(); }); }); }); });
这是我的舞台经理
var Staging = function(mongoose) { this.mongoose = mongoose; }; Staging.prototype.getStaging = function() { return this.mongoose.model('CheckStaging', { user: String, createdAt: { type: Date, default: Date.now } }); }; module.exports = Staging;
mongoose.model
用Mongoose注册一个模型,所以你只应该调用一次,而不是每次调用getStaging。 尝试像这样为您的分期模型,而不是:
var mongoose = require('mongoose'); var StagingModel = new mongoose.Schema({ user: String, createdAt: { type: Date, default: Date.now } }); mongoose.model('CheckStaging', StagingModel);
然后在你的消费代码中,使用
var mongoose = require('mongoose'); require('../lib/staging_manager'); var StagingModel = mongoose.model('CheckStaging');
要求只会执行一次,所以模型只能loginmongoose一次。
另外,unit testing,mockgoose是一个很好的嘲笑库嘲笑mongoose值得调查!