我有两个简单的测试,但是其中一个测试通过但不是另一个,因为Schema再次编译。
OverwriteModelError:无法覆盖
CheckStaging
模型一次 编译。
这是我的一个测试,因为它首先被运行。
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();
});
});
});
});
这是失败的测试
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;
答案 0 :(得分:1)
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');
require仅执行一次,因此模型只能用mongoose注册一次。
另外,对于单元测试,mockgoose是一个非常好的模拟库来模拟猫鼬 - 值得调查!