Jest测试执行dropDatabase后报MongoExpiredSessionError问题求助
问题:Jest afterAll中执行数据库删除后关闭Mongoose连接出现MongoExpiredSessionError错误
在Jest测试的afterAll函数中,我先执行数据库删除操作,再关闭Mongoose连接,但出现了MongoExpiredSessionError错误。
相关代码:
afterAll(async ()=>{ await mongoose.connection.db.dropDatabase((err)=>{console.error(err)}); mongoose.disconnect(); });
错误信息:
MongoExpiredSessionError: Cannot use a session that has ended at applySession (/home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/sessions.ts:978:12) at Connection.command (/home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/cmap/connection.ts:519:31) at /home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/sdam/server.ts:365:14 at Object.callback (/home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/cmap/connection_pool.ts:513:7) at ConnectionPool.processWaitQueue (/home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/cmap/connection_pool.ts:689:25) at /home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/cmap/connection_pool.ts:357:33 at processTicksAndRejections (node:internal/process/task_queues:77:11) { [Symbol(errorLabels)]: Set(0) {} }
明明已经用await等待数据库删除完成,为什么disconnect还是会提前执行?该如何解决?
原因分析
问题出在dropDatabase的调用方式上:当你给dropDatabase传入回调函数时,它会以回调模式运行,不会返回Promise对象。这意味着你写的await实际上没有等待任何异步操作完成,代码会直接跳到mongoose.disconnect()执行,导致数据库连接提前关闭。而此时dropDatabase的回调还在尝试使用已结束的会话,就抛出了MongoExpiredSessionError。
解决方法
方案1:使用Promise形式(推荐)
去掉回调函数,让dropDatabase返回Promise,用await等待它执行完成;同时mongoose.disconnect()也是异步操作,最好也加上await确保所有操作完成:
afterAll(async ()=>{ try { await mongoose.connection.db.dropDatabase(); } catch (err) { console.error(err); } await mongoose.disconnect(); });
方案2:使用回调模式的正确写法
如果一定要用回调,需要在dropDatabase的回调函数内部执行disconnect,并利用Jest的done参数通知测试框架异步操作完成:
afterAll((done)=>{ mongoose.connection.db.dropDatabase((err)=>{ if (err) console.error(err); mongoose.disconnect(done); }); });
内容的提问来源于stack exchange,提问作者Lee Morgan
相关产品推荐
相关产品推荐

