jest and mongoose - jest has detected opened handles jest and mongoose - jest has detected opened handles mongoose mongoose

jest and mongoose - jest has detected opened handles


It's related to model.init function which returns promise. Quick fix will be to pass skipInit flag while creating the model like this:

const User = mongoose.model("users", userSchema, "users", true)

skipInit is the fourth parameter in this function

But in this case it will not initialize indexes for your model, so it's better to set this flag according to the process.env.NODE_ENV

const skipInit = process.env.NODE_ENV === "test"const User = mongoose.model("users", userSchema, "users", skipInit)


It seems your mongoose connection remains open after your test, try one of the following:

  1. close server instance after test.

    const server = require('./app'); //server instance    server.close(); //put in afterAll or afterEach depending on your test
  2. close your database connection after all your test.

    afterAll(()=>{ mongoose.connection.close();});
  3. wrap your mongoose connection with async/await.

    async function(){   await mongoose.connect(mongoDB);};

try one or a combination.These are my solutions since I can't really see your code.