4

I am using express and connect via the npm package "mongodb": "^3.0.10" to a mongodb.

My app.ts looks like this:

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;

For testing i use jest and supertest. The tests run successfully, but they never end, because there are still connections to mongodb.

The tests look something like this:

describe("user routes", 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);
});

I understand, that the mongodb driver uses connection pooling and the way i pass the db- (or collection-) object to my user repository, makes it impossible to close the connections manually in a test scenario.

I guess a need a better way a pass the db connection to my user repository, but i can not think of a better, or more decoupled way at the moment.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
user2534584
  • 483
  • 2
  • 8
  • 15

1 Answers1

0

Try await mongoClient.close() after your tests are done. See MongoDB docs. As far as I know, Jest supports before() and after() hooks, and I imagine before() and after() hooks support async/await like Mocha's do.

vkarpov15
  • 3,614
  • 24
  • 21