node.js - Mocha 单元测试 Mongoose 模型

标签 node.js mongodb unit-testing mongoose mocha.js

我正在努力找出为我的 NodeJS 应用程序编写这些单元测试的正确(即不是黑客)方法。

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

关于node.js - Mocha 单元测试 Mongoose 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404903/

相关文章:

node.js - 在 Node.js 中使用 Crypto 加密未给出预期结果

mongodb - 未知函数选择位于/tmp/vagrant-puppet/modules-84c36838170137b342ad08a194e8c35b/mongodb/manifests/params.pp :6 on node - Vagrant

c - 嵌入式系统到 Web 输出的 Unity 测试

mongodb - 获取查询中所有文档的大小

python - 从 pymongo.objectid 导入 ObjectId 导入错误 : No module named objectid

java - 错误 : Could not find or load main class org. testng.remote.RemoteTestNG

.net - 使用 dotCover 时测试结果不一致

angularjs - 如何使用nginx来提高nodejs的性能

javascript - GraphQL 突变仅返回一个结果

node.js - Socket.IO 消息传递到多个房间