9

I have the following error after running my tests with --detectOpenHandles parameter

 Jest has detected the following 1 open handle potentially keeping Jest from exiting:

 ●  PROMISE

  18 |
  19 | mongoose.Promise = global.Promise;
> 20 | mongoose.connect(config.database.link, config.database.options);
     |          ^
  21 |
  22 |
  23 | app.use(cors());

But my test includes mongoose.disconnect()

afterAll(() => {
  return new Promise(res => mongoose.disconnect(() => {
    res();
  }));
});

I tried to change the afterAll function to something like this:

afterAll(async () => {
  await mongoose.disconnect();
  await mongoose.connection.close();
});

Also I tried to call con.disconnect inside of afterAll()

app.con = mongoose.connect(config.database.link, config.database.options);

// inside of afterAll
app.con.disconnect() 

But I am still getting the same error message as shown above

Fiehra
  • 659
  • 6
  • 23
Yuri Taratorkin
  • 607
  • 6
  • 19
  • 2
    Possible duplicate of [jest and mongoose - jest has detected opened handles](https://stackoverflow.com/questions/50687592/jest-and-mongoose-jest-has-detected-opened-handles) – Gianfranco P. Jul 24 '18 at 10:13
  • did you find a solution? i tried solutions as in other posts but they didn work for me – Fiehra Feb 16 '22 at 11:32

1 Answers1

0

Id like to reference @ÖzgürAtmaca 's answer from this question: https://stackoverflow.com/a/73673422/11895459

I started using this answer instead of my own solution which was only a workaround and not fit for any environment except locally.

By disconnecting before reconnecting to the database the error is gone.

beforeAll(async () => {
  await mongoose.disconnect();
  await mongoose.connect(url, {});
});


afterAll(async () => {
  await mongoose.disconnect();
});
Fiehra
  • 659
  • 6
  • 23