草庐IT

javascript - 为 Mongoose 运行多个 Mocha 测试文件被打破

coder 2023-11-06 原文

根据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();
            });
        });
    });
});

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

此外,我与数据库的连接在 ../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 上测试它们时,测试因错误(错误:尝试打开未关闭的连接。)而中断,如下所示。它发生在 Mocha 尝试测试 user.server.model.js 时。

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

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

这是 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();
            });
        });
    });
});

最佳答案

我发现捕获错误可以为我解决这个问题。这可能是一个 Mocha 错误?无论如何,这是有效的,不值得我花时间进一步调查。我希望这会解锁其他人。

注意我是如何将回调传递给连接函数的:

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) {
   });
})

关于javascript - 为 Mongoose 运行多个 Mocha 测试文件被打破,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35170626/

有关javascript - 为 Mongoose 运行多个 Mocha 测试文件被打破的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  4. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  5. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  6. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  7. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  8. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  9. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  10. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

随机推荐