【问题标题】:Closing a MongoDB connection after running Mocha tests for an Express application在为 Express 应用程序运行 Mocha 测试后关闭 MongoDB 连接
【发布时间】:2020-09-06 01:12:33
【问题描述】:

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

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。

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

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

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

after(async () => {

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

after 钩子关闭了我与 RDBMS 的连接。

但是,我不知道如何在测试完成后关闭 MongoDB 连接。

由于保持此连接打开,一旦运行所有测试,测试就永远不会退出并挂起。

我能找到的最接近的答案是这个 - Keep MongoDB connection open while running tests using mocha framework

但是,我无法为自己工作。

有人可以帮忙吗?

更新 以下答案的组合就是解决问题的方法。

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
}

【问题讨论】:

    标签: node.js mongodb express mocha.js


    【解决方案1】:

    我们可以重写mongo函数让它工作

    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(async () => {
    
        await app.knex.destroy();
        await client.close();
    
    });
    

    【讨论】:

    • 最好在 module.exports 中添加clientmodule.exports = { server, knex, client };。所以可以关闭:await app.client.close(); ;)
    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 2012-05-26
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多