node.js - MongoDB 连接在测试场景中不会关闭

标签 node.js mongodb express jestjs supertest

我正在使用 express 并通过 npm 包 "mongodb": "^3.0.10" 连接到 mongodb。

我的 app.ts 看起来像这样:

const app = express();
let server: http.Server;
(async () => {
    app.use(bodyParser.json());

    let db: Db;

    try {
        const host = config.get<string>("api.dbConfig.host");
        console.log(host);
        const dbName = config.get<string>("api.dbConfig.dbName");
        const port = config.get<string>("api.dbConfig.port");
        const connectionString = "mongodb://" + host + ":" + port;
        const mongoClient = await MongoClient.connect(connectionString);
        db = mongoClient.db(dbName);
        await db.collection("users").createIndex({email: 1}, {unique: true});
    }
    catch (err) {
        console.log(err);
        console.log("can not connect to MongoDB");
    }

    const userRepo = new UserRepository(db);

    // Routes
    app.use("/v1/users", userRoutes(userRepo));

    server = http.createServer(app);
    server.listen(3000);
    server.on("listening", () => {
        console.log("listening");
    });
})();
module.exports = app;

为了测试,我使用 jest 和 supertest。测试成功运行,但它们永远不会结束,因为仍然存在与 mongodb 的连接。

测试看起来像这样:

describe("用户路由", function () {

it("should return all users", async () => {
    const response = await agent(app).get("/v1/users/");
    expect(response.status).to.be.equal(200);
    expect(response.body).to.be.an("array");
    expect(response.body).to.have.lengthOf(2);
});

我知道,mongodb 驱动程序使用连接池以及我将 db-(或集合-)对象传递到我的用户存储库的方式,使得无法在测试场景中手动关闭连接。

我想我需要一种更好的方法来将数据库连接传递到我的用户存储库,但我目前想不出更好的或更解耦的方法。

最佳答案

在测试完成后尝试 await mongoClient.close()。参见 MongoDB docs .据我所知,Jest 支持 before()after() 钩子(Hook),我想象 before()after( ) 钩子(Hook)支持异步/等待,如 Mocha's do .

关于node.js - MongoDB 连接在测试场景中不会关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50924173/

相关文章:

Express.js 应用程序无服务器,使用 Lambda 或函数 - 一个好主意?

javascript - Node.js:如何从请求正文中获取调用 POST 的页面的 URL?

node.js - 无法让部署的 pdf 模块工作 dpd-pdf

node.js - 中间件实际上是如何工作的?

mongodb - 如何在mongodb中聚合时间序列文档

xml - 如何使用 Node 转换流将 XML 转换为 JSON

javascript - .bowerrc 中的 Bower 多个注册表 URL

javascript - NodeJS - 在 setTimeout 内等待返回

node.js - Mongoose 尝试从其他文件加载模型时出错

node.js - Swagger + Node.js 的异步验证功能