摩卡单位testingmongoose模型

我正在努力弄清楚为我的NodeJS应用程序编写这些unit testing的正确(即不是黑客)的方式。

在server.js中,我将mongoose连接到本地主机上运行的数据库:27017。 当我运行我的mochatesting时,我想连接到在localhost:37017上运行的不同 mongoDB实例,以便我不针对活动数据库运行testing。 当我在test.js中需要mongoose并且尝试连接时,mongoose会抛出一个错误,说“尝试打开未closures的连接”。

我已经尝试closurestest.js中的当前连接,但由于某种原因无法正常工作。

我的问题是:什么是正确的方式来连接到一个文件中的testing数据库,但继续让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) }); }); 

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

 // 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处理程序中加载模型,否则可能会“连接”到原始连接。

再一次,这仍然是一个黑客,我build议将你的数据库的configuration移动到某种外部configuration文件,或使用一个环境variables,这可能是相对容易实现:

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