2016-07-15 142 views
1

我正在努力弄清楚为我的NodeJS应用程序编写这些单元测试的正确方法(即不是破解)。摩卡单元测试猫鼬模型

在server.js中,我将猫鼬连接到本地主机上运行的数据库:27017。当我运行我的摩卡测试时,我想连接到不同的在localhost:37017上运行的mongoDB实例,以便我不针对实时数据库运行我的测试。当我在test.js中需要猫鼬并尝试连接时,猫鼬会抛出错误,并说“尝试打开未关闭的连接”。

我已经尝试关闭test.js中的当前连接,但它由于某种原因不起作用。

我的问题是:什么是正确的方式来连接到一个文件中的测试数据库,但继续让server.js连接到实时数据库?

我的代码如下:

// test.js 
var app = require('../lib/server') // This connects mongoose to a database 
var assert = require('assert'); 
var httpstatus = require('http-status'); 
var superagent = require('superagent'); 

// Connect to mongoose 
var mongoose = require('mongoose'); 
mongoose.connect('mongodb://localhost:37017/testDB'); // THIS THROWS ERROR because server.js is connecting to localhost:27017/liveDB 

// Models we will be testing 
var thing = require('../models/thing.js'); 

describe('Thing', function() { 

    before(function() { 
     // Clear the database here 
    } 

    beforeEach(function() { 
     // Insert, modify, set up records here 
    } 

    it('saves the thing to the database', function() { 
     // Save and query a thing here (to the test DB) 
    }); 
}); 
+0

通常,这些东西都是在您的应用程序外部配置的,因此您在测试过程中会使用不同的配置。但是作为一个快速入侵(对不起......),你可以在你的测试文件中调用'.connect()'之前试着看看'mongoose.disconnect()'是否工作。 – robertklep

+0

在连接到数据库之前,即使使用'mongoose.disconnect()',它仍会抛出“试图打开未关闭的连接”错误。 您是否可以修改如何设置您提到的配置文件?我是一个非常新的(少于2周)节点开发人员 – ellman121

回答

1

你可以试试这个(虽然这是一个黑客):

// Connect to mongoose 
var mongoose = require('mongoose'); 
before(function(done) { 
    mongoose.disconnect(function() { 
    mongoose.connect('mongodb://localhost:37017/testDB'); 
    done(); 
    }); 
}); 

// Models we will be testing (see text) 
var thing = require('../models/thing.js'); 

... 

describe(...) 

它可能需要载入disconnect处理器内部模型以及作为否则可能会“附加”到原始连接。

同样,这还是相当一个黑客,我会建议你的数据库的配置移动到的某些种类的外部配置文件,或者使用环境变量,这可能是比较容易实现的:

// server.js 
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost:27017/prodDB') 

// test.js 
process.env.MONGO_URL = 'mongodb://localhost:37017/testDB' 
var app = require('../lib/server');