我正在使用 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/