首页 > 解决方案 > 如何在开玩笑测试中正确关闭猫鼬连接

问题描述

使用 --detectOpenHandles 参数运行测试后出现以下错误

 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());

但我的测试包括 mongoose.deisconnect()

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

我试图将 afteAll 函数更改为这样的东西

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

我也尝试在 afterAll() 内部调用 con.disconnect

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

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

但我仍然看到这个错误

如何解决?

标签: mongodbtestingmongoosejestjs

解决方案


推荐阅读