【问题标题】:MongoDB connections do not close in test scenariosMongoDB 连接在测试场景中不关闭
【发布时间】:2018-11-28 04:01:30
【问题描述】:

我正在使用 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-(或 collection-)对象传递给我的用户存储库的方式,使得无法在测试场景中手动关闭连接。

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

【问题讨论】:

    标签: node.js mongodb express jestjs supertest


    【解决方案1】:

    测试完成后尝试await mongoClient.close()。见MongoDB docs。据我所知,Jest 支持 before()after() 钩子,我想 before()after() 钩子支持 async/await 就像 Mocha's do

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      相关资源
      最近更新 更多