为Mongoose运行多个Mocha测试文件已被破坏

时间:2016-02-03 07:10:00

标签: javascript node.js mongodb mongoose mocha

根据Alexey B.的评论,我修改了我的测试代码并发现导致我的测试代码出现同样错误的情况。当我尝试测试单个测试文件时,它运行良好。但是,如果我尝试同时测试多个测试文件,它就会被破坏。常见错误消息是Error: Trying to open unclosed connection.。我的数据库连接代码似乎有些问题。

这是我修改后的代码。

utils.js

var mongoose = require('mongoose');
module.exports = function(models) {
    return function(done) {
        for(var i in models) {
            models[i].remove({}, function() {});
        }
        done();
    };
};

user.server.model.tests.js

var should = require('should'),
    mongoose = require('mongoose'),
    utils = require('./utils');

require('../config/mongoose')();
var User = mongoose.model('User'),
    user;

describe('User Model Tests:', function() {
    afterEach(utils([User]));

    describe('#create()', function() {
        beforeEach(function(done) {
            user = new User({
                email:'test1@test.com',
                username: 'test1',
                password: '1234'
            });
            done();
        });

        it('create a new user', function(done) {
            user.save(function(err, user) {
                should.not.exist(err);
                user.email.should.equal('test1@test.com');
                user.username.should.equal('test1');
                done();
            });
        });

        it('create a new user with an existing email', function(done) {
            user.save(function(err) {
                should.not.exist(err);
            });

            var userDUP = new User({
                email:'test1@test.com',
                username:'test2',
                password: '1234'
            });

            userDUP.save(function(err) {
                should.exist(err);
                done();
            });
        });
    });
});

product.server.model.tests.js

var should = require('should'),
    mongoose = require('mongoose'),
    utils = require('./utils');

require('../config/mongoose')();

var Product = mongoose.model('Product'),
    User = mongoose.model('User');

describe('Product Model Tests:', function(){
    afterEach(utils([User, Product]));
    describe('#create()', function(){
        it('create a new product', function(done) {
            var user = new User({
                email:'test@test.com',
                username: 'test',
                password: '1234'
            });

            user.save(function(err) {
                should.not.exist(err);
            });

            var product = new Product({
                name: 'Product1',
                user: user
            });

            product.save(function(err, product) {
                should.not.exist(err);
                User.findOne({'_id':product.user}, function(err, user) {
                    should.not.exist(err);
                    user.username.should.equal('test');
                });
                product.name.should.equal('Product1');
                product.ordered.should.equal(0);
                product.stock.should.equal(0);

                done();
            });
        });

        it('create a new product without a user', function(done) {
            var product = new Product({
                name: 'Product'
            });

            product.save(function(err){
                should.exist(err);
                done();
            });
        });
    });
});

我还有两个测试文件,但它们的结构是相同的。

此外,我对DB的连接在../config/mongoose.js中定义。这是代码。

var config = require('./config'),
    mongoose = require('mongoose');

module.exports = function() {
    var db = mongoose.connect(config.db);
    console.log('MongoDB is successfully connected.');

    require('../models/user.server.model');
    require('../models/product.server.model');
    require('../models/sale.server.model');
    require('../models/dcompany.server.model');
    require('../models/customer.server.model');

    return db;
};

我尝试使用createConnect而不是connect来连接数据库,但它引发了另一个名为timeout的错误。

以下是此问题的旧版本。

我有两个测试文件(“product.server.model.tests.js”和“user.server.model.tests.js”),两个调用“utils.js”包含beforeEachafterEach连接/已断开数据库已完成。

当我进行Mocha测试的运行/调试配置并尝试在Webstorm 11上测试它们时,测试中断了错误(Error: Trying to open unclosed connection.),如下所示。当Mocha试图测试user.server.model.js时会发生这种情况。

enter image description here

但是,当我在终端上运行这些测试时,它会通过所有测试! (见下文)另外,如果我为每个测试文件单独进行运行/调试配置,也没有问题。

enter image description here

我在Webstorm 11上的运行/调试配置如下所示。

enter image description here

它有点像Webstorm 11的错误吗?或者在设置运行/调试配置或我的测试代码时出错?我在下面附上了我的测试代码。

utils.js

var mongoose = require('mongoose');

beforeEach(function(done) {
    require('../config/mongoose')();

    for(var i in mongoose.connection.collections) {
        mongoose.connection.collections[i].remove(function() {});
    }

    done();
});

afterEach(function(done) {
    mongoose.disconnect();
    done();
});

user.server.model.test.js

require('./utils');
var should = require('should'),
    mongoose = require('mongoose');

describe('User Model Tests:', function() {
    describe('#create()', function() {
        it('create a new user', function(done) {
            var User = mongoose.model('User');

            var user = new User({
                email:'test1@test.com',
                username: 'test1',
                password: '1234'
            });

            user.save(function(err, user) {
                should.not.exist(err);
                user.email.should.equal('test1@test.com');
                user.username.should.equal('test1');
                done();
            });
        });

        it('duplication: email', function(done) {
            var User = mongoose.model('User');

            var user = new User({
                email:'test1@test.com',
                username: 'test1',
                password: '1234'
            });

            user.save(function(err) {
                should.not.exist(err);
            });

            var userDUP = new User({
                email:'test1@test.com',
                username:'test2',
                password: '1234'
            });

            userDUP.save(function(err) {
                should.exist(err);
                done();
            });
        });
    });
});

product.server.model.tests.js

require('./utils');
var should = require('should'),
    mongoose = require('mongoose');

describe('Product Model Tests:', function(){
    describe('#create()', function(){
        it('create a new product', function(done) {
            var Product = mongoose.model('Product');
            var User = mongoose.model('User');

            var user = new User({
                email:'test@test.com',
                username: 'test',
                password: '1234'
            });

            user.save(function(err) {
                should.not.exist(err);
            });

            var product = new Product({
                name: 'Product1',
                user: user
            });

            product.save(function(err, product) {
                should.not.exist(err);
                User.findOne({'_id':product.user}, function(err, user) {
                    should.not.exist(err);
                    user.username.should.equal('test');
                });
                product.name.should.equal('Product1');
                product.ordered.should.equal(0);
                product.stock.should.equal(0);

                done();
            });
        });

        it('create a new product without a user', function(done) {
            var Product = mongoose.model('Product');

            var product = new Product({
                name: 'Product'
            });

            product.save(function(err){
                should.exist(err);
                done();
            });
        });
    });
});

3 个答案:

答案 0 :(得分:1)

我发现捕获错误可以解决这个问题。这可能是一个摩卡虫?无论如何这是有效的,我不值得进一步调查。我希望这能阻止其他人。

注意我如何将回调传递给connect函数:

var mongoose = require('mongoose');

...

before(function (done) {
    mongoose.connect('mongodb://localhost/test', function(err) {
        done();
    });
});

after(function (done) {
    mongoose.connection.close();
    done();
});

describe('some tests', function() {
   it('can do something', function (done) {
   });
})

答案 1 :(得分:0)

不能确切地说这是问题,但在单独的文件中实现mocha挂钩是一种不好的做法。例如,然后您向项目添加更多测试,您无法禁用某些不需要数据库连接的测试的挂钩。

这里正确的方法是制作一些辅助模块

module.exports = {
    connect: function (done) {
        require('../config/mongoose')();

        for(var i in mongoose.connection.collections) {
            mongoose.connection.collections[i].remove(function() {});
        }

        done();
    },

    disconnect: function (done) {
        mongoose.disconnect();
        done();
    }
};

并在测试中应用

var should = require('should'),
    mongoose = require('mongoose'),
    helper = require('./utils');

describe('User Model Tests:', function() {
    beforeEach(helper.connect);
    afterEach(helper.disconnect);
    describe('#create()', function() {
        ...
    });
});

答案 2 :(得分:0)

我重构了我的测试代码,引用了问题“joining tests from multiple files with mocha.js”。我构建了一个test.js来加入所有不同的测试文件,并且在test.js的开头,已尝试连接到数据库。这是我的工作测试代码。

test/test.js

var mongoose = require('mongoose');

var importTest = function(name, path) {
    describe(name, function() {
        require(path);
    });
};

//Connecting to the DB
require('../../app/config/mongoose')();

describe("Model Testing:", function() {
    before(function() {
        console.log('Start a model testing!\n');
    });

    importTest('User Model Testing:', './models/user.server.model.tests');
    importTest('Sale Model Testing:', './models/sale.server.model.tests');
    importTest('Product Model Testing:', './models/product.server.model.tests');
    importTest('DCompany Model Testing:', './models/dcompany.server.model.tests');

    after(function() {
        mongoose.disconnect();
        console.log("Disconnect to the DB.\n");
    })
});

/test/models/user.server.model.tests.js

var should = require('should'),
    mongoose = require('mongoose'),
    utils = require('./utils');

var User = mongoose.model('User'),
    user;

afterEach(utils([User]));
describe('#create()', function() {
    beforeEach(function(done) {
        user = new User({
            email:'test1@test.com',
            username: 'test1',
            password: '1234'
        });
        done();
    });

    it('create a new user', function(done) {
        user.save(function(err, user) {
            should.not.exist(err);
            user.email.should.equal('test1@test.com');
            user.username.should.equal('test1');
            done();
        });
    });

    it('create a new user with an existing email', function(done) {
        user.save(function(err) {
            should.not.exist(err);
        });

        var userDUP = new User({
            email:'test1@test.com',
            username:'test2',
            password: '1234'
        });

        userDUP.save(function(err) {
            should.exist(err);
            done();
        });
    });
});

其他测试文件的结构与user.server.model.tests.js类似。