【发布时间】:2016-11-19 04:23:33
【问题描述】:
我正在努力找出为我的 NodeJS 应用程序编写这些单元测试的正确方法(即不是 hack)。
在 server.js 中,我将 mongoose 连接到在 localhost:27017 上运行的数据库。当我运行 mocha 测试时,我想连接到在 localhost:37017 上运行的 不同 mongoDB 实例,这样我就不会针对实时数据库运行测试。当我在 test.js 中需要 mongoose 并尝试连接时,mongoose 会抛出错误,说“尝试打开未关闭的连接。”
我曾尝试关闭 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)
});
});
【问题讨论】:
-
一般来说,这些东西是在你的应用程序之外配置的,所以你会在测试时使用不同的配置。但作为一个快速破解(抱歉...),您可以在测试文件中调用
.connect()之前尝试查看mongoose.disconnect()是否有效。 -
即使在我连接到数据库之前使用
mongoose.disconnect(),它仍然会引发“尝试打开未关闭的连接”错误。您能否详细说明如何设置您提到的配置文件?我是一个非常新的(不到 2 周)节点开发人员
标签: node.js mongodb unit-testing mongoose mocha.js