如何在玩笑测试中正确关闭猫鼬连接

yur*_*snk 10 testing mongoose mongodb node.js jestjs

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

\n
 Jest has detected the following 1 open handle potentially keeping Jest from exiting:\n\n \xe2\x97\x8f  PROMISE\n\n  18 |\n  19 | mongoose.Promise = global.Promise;\n> 20 | mongoose.connect(config.database.link, config.database.options);\n     |          ^\n  21 |\n  22 |\n  23 | app.use(cors());\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
afterAll(() => {\n  return new Promise(res => mongoose.disconnect(() => {\n    res();\n  }));\n});\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试将 afterAll 函数更改为如下所示:

\n
afterAll(async () => {\n  await mongoose.disconnect();\n  await mongoose.connection.close();\n});\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
app.con = mongoose.connect(config.database.link, config.database.options);\n\n// inside of afterAll\napp.con.disconnect() \n
Run Code Online (Sandbox Code Playgroud)\n

但我仍然收到与上面所示相同的错误消息

\n

Fie*_*hra 0

我想引用@\xc3\x96zg\xc3\xbcrAtmaca \的这个问题的答案:/sf/answers/5157139571/

\n

我开始使用这个答案而不是我自己的解决方案,这只是一种解决方法,不适合除本地以外的任何环境。

\n

通过在重新连接到数据库之前断开连接,错误就消失了。

\n
beforeAll(async () => {\n  await mongoose.disconnect();\n  await mongoose.connect(url, {});\n});\n\n\nafterAll(async () => {\n  await mongoose.disconnect();\n});\n
Run Code Online (Sandbox Code Playgroud)\n