摩卡单元测试猫鼬模型

时间:2016-07-15 20:57:33

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

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

在server.js中,我将mongoose连接到localhost:27017上运行的数据库。当我运行我的mocha测试时,我想连接到运行在localhost:37017上的不同的 mongoDB实例,这样我就不会对实时数据库运行我的测试。当我在test.js中需要mongoose并尝试连接时,mongoose会抛出一个错误,说"尝试打开未关闭的连接。"

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

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

我的代码如下:

//Iterating over all the char*
for (x = 0; x < 5; x++)
{
        printf("\nPrintTest 4");

        //Printing the arrays without the loop
        printf("\nPrintTest 5");
        printf("Name: %s", names[x]);
        printf("\nPrintTest 6");
}

2 个答案:

答案 0 :(得分: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');

答案 1 :(得分:0)

npm i env-cmd --save   // install this package

在项目根目录中创建config目录,并在config文件夹中创建dev.env和test.env文件。

在test.env文件中,如下配置测试环境:

PORT=4000

MONGODB_URL=mongodb://127.0.0.1:27017/dbTestName

然后在package.json中,将test.env的设置加载到测试环境中。

"test": "env-cmd  -f ./config/test.env jest --watchAll --runInBand"

在这里我们需要模块,然后在此处加载test.env设置。

env-cmd软件包将根据您的环境将.env文件中的所有设置添加到process.env对象中。当您运行run npm test时,您的应用将使用test.env中的设置。

因此在您的应用程序中,这就是应该使用MONGODB_URL连接猫鼬的方式。

mongoose
  .connect(process.env.MONGODB_URL, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false
  })
  .catch(err => {
    console.log(err.message);
    process.exit(1);
  })
  .then(() => {
    console.log("connected to mongodb");
  });

您将在dev.env中使用适用于您的开发环境的设置。现在您需要调整package.json中的dev脚本

"dev": "env-cmd -f ./config/dev.env node src/index.js",

现在运行时

npm run dev

您的应用从dev.env加载设置

相关问题