在为Express应用程序运行Mocha测试后关闭MongoDB连接 [英] Closing a MongoDB connection after running Mocha tests for an Express application

查看:149
本文介绍了在为Express应用程序运行Mocha测试后关闭MongoDB连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的Express应用程序.

I have an Express application that looks like this.

const app = express();

...
...
...

router.post(...);
router.get(...);
router.delete(...);

app.use('/api/v1', router);

MongoClient.connect(mongoUri, { useNewUrlParser: true })
    .then(client => {
        const db = client.db('db_name');
        const collection = db.collection('collection_name');
        app.locals.collection = collection;
    })
    .catch(error => console.error(error));

const server = app.listen(settings.APIServerPort, () => console.log(`Server is listening on port ${settings.APIServerPort}.`));

module.exports = {

    server,
    knex // using this to connect to the RDBMS
}

该应用程序同时使用RDBMS和Mongo.

The application uses both an RDBMS and Mongo.

我使用Mocha为应用程序编写了测试,并将以下代码块添加到Mocha测试中.

I wrote tests for the application using Mocha and added the following block to the Mocha test.

const app = require('../app');

...test 1...
...test 2...
...test 3...
...
...
...
...test n...

after(async () => {

    await app.knex.destroy();
});

after钩关闭了我与RDBMS的连接.

The after hook closes out my connection to the RDBMS.

但是,一旦测试完成,我不知道如何关闭MongoDB连接.

However, I don't know how to close the MongoDB connection once the test finishes.

由于此连接保持打开状态,因此在运行所有测试之后,该测试就永远不会退出并挂起.

Owing to keeping this connection open, the test never exits and hangs once all the tests have been run.

我能找到的最接近的答案就是这个-

The closest answer that I have been able to find is this one - Keep MongoDB connection open while running tests using mocha framework.

但是,我无法为我工作.

However, I was unable to get to work for me.

有人可以帮忙吗?

更新 解决这些问题的方法是结合以下答案.

Update A combination of the answers below is what solved the problem.

const mongoClient = new MongoClient(mongoUri, { useNewUrlParser: true });

mongoClient.connect()
    .then(client => {
        const db = client.db('...');
        const collection = db.collection('...');
        app.locals.collection = collection;
    })
    .catch(error => console.error(error));

const server = app.listen(settings.APIServerPort, () => console.log(`Server is listening on port ${settings.APIServerPort}.`));

module.exports = {

    server,
    knex, 
    mongoClient
}

推荐答案

我们可以重写mongo函数以使其正常工作

We can rewrite the mongo function to make it work

const client = new MongoClient(uri);

client.connect()
    .then(client => {
        const db = client.db('db_name');
        const collection = db.collection('collection_name');
        app.locals.collection = collection;
    })
    .catch(error => console.error(error));

在after块中-

after(async () => {

    await app.knex.destroy();
    await client.close();

});

这篇关于在为Express应用程序运行Mocha测试后关闭MongoDB连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆