【问题标题】:Mongoose doesn't drop database and close connection properly in MochaMongoose 不会在 Mocha 中正确删除数据库并关闭连接
【发布时间】:2015-07-30 16:52:26
【问题描述】:

我有两个简单的测试,但其中一个通过了,但另一个没有通过,因为架构再次被编译。

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;

【问题讨论】:

    标签: javascript node.js mongodb asynchronous mocha.js


    【解决方案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 是一个用于模拟 mongoose 的出色模拟库 - 值得研究!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2018-01-30
      • 2019-04-14
      • 1970-01-01
      相关资源
      最近更新 更多