在Mocha中,Mongoose不能正确地删除数据库并关闭连接

Mongoose doesn't drop database and close connection properly in Mocha

本文关键字:数据库 连接 删除 正确地 Mocha Mongoose 不能      更新时间:2023-09-26

我有两个简单的测试,但其中一个测试通过了,但另一个测试没有通过,因为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;

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');

请求只执行一次,所以模型应该只注册一次。

作为题外话,对于单元测试,mockgoose是一个模拟猫鼬的优秀模拟库——值得研究!