MongoError: pool is draining, new operations prohibited when using MongoMemoryServer in integration test MongoError: pool is draining, new operations prohibited when using MongoMemoryServer in integration test mongoose mongoose

MongoError: pool is draining, new operations prohibited when using MongoMemoryServer in integration test


By default Jest runs tests in parallel with a “a worker pool of child processes that run tests” (Jest CLI docs). As per the Jest documentation.

Each test file is making a new connection to the mogodb server which is causing the error.

You could run the Jest test sequentially to avoid this issue.

The --runInBand or -i option of the Jest CLI allows you to run tests sequentially (in non-parallel mode).

This error (pool is draining, new operations prohibited) might occur if you are using the official mongodb library for node js or mongoose. Please specifying pool size while establishing mongodb connection.

module.exports.connect = async () => {  const uri = await mongod.getConnectionString();  const mongooseOpts = {    useNewUrlParser: true,    autoReconnect: true,    reconnectTries: Number.MAX_VALUE,    reconnectInterval: 1000,    poolSize: 10,  };  await mongoose.connect(uri, mongooseOpts);};


I did the same way and faced into the same error.This was resolved by removing by schema name in test only like I did below in some.test.js

** Rest all setup remains same **

//example.it.test.jsconst dbHandler = require("./db-handler");const SomeModel = require("../Some");const SomeOtherModel = require("../SomeOther");beforeAll(async () => await dbHandler.connect());afterEach(async () => {  await SomeModel.remove({});  await SomeOtherModel.remove({});});afterAll(async () => await dbHandler.closeDatabase());describe("Some Test Block", () => {  it("Test One", async (done) => {    await SomeModel.create({a: "a", SomeOther: 'SomeOther Data' });    const data = await SomeModel.getAll();    expect(data.length).toBe(1);    done();  });});


For every It test case, it connects to the mongoose, and if any error occurred, mongoose does not disconnect.

Solution

  1. You can put the it test case in the try catch block, but if possible use 2 point
  2. Try to handle the error in the controllers and service, and so onfiles if possible.
  3. And whenever you write test case, there should be no error comes from the development code.
  4. Don't write nested describe in a single describe, max 2 nesteddescribe we should use.
  5. One temporary solution, I skip the all describe expect outmost where mongoose was connected.
  6. One more temporary solution, disconnect the mongod and then see the status, then reconnect.

Please let me know if this helped you.