NestJS BullMQ Worker Processor与Jest测试兼容问题:无法正常退出
问题:Jest测试因BullMQ Worker无法正常退出
问题描述
使用NestJS + BullMQ编写测试用例时,测试执行完成后Jest始终无法退出,抛出报错:
Jest did not exit one second after the test run has completed. 'This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
仅将Worker的自定义处理器替换为空字符串时,测试能正常退出,说明自定义处理器的存在导致异步资源未被彻底清理。
解决方案
方案1:强制关闭Worker并调整资源销毁顺序
修改AppService中的disconnect方法,优先强制关闭Worker,再清理队列和Redis连接:
async disconnect(): Promise<void> { // 强制关闭Worker,终止所有后台轮询与异步任务 await this.worker.close(true); // 关闭队列连接 await this.queue.close(); // 最后关闭Redis实例 await this.redis.quit(); }
方案2:先停止轮询再关闭Worker
若不需要强制终止任务,可先主动停止Worker的任务轮询逻辑,再执行关闭操作:
async disconnect(): Promise<void> { // 停止Worker的Redis任务轮询 await this.worker.stop(); // 等待Worker完成内部资源清理 await this.worker.close(); // 关闭队列连接 await this.queue.close(); // 关闭Redis实例 await this.redis.quit(); }
原因分析
当Worker配置自定义处理器后,BullMQ会启动后台轮询进程,持续从Redis拉取待处理任务。即使没有任务待执行,这个轮询机制仍会维持异步定时器或Redis订阅连接。默认的worker.close()无法立即终止这些后台进程,导致Jest检测到未完成的异步操作,从而无法正常退出。
使用close(true)可强制终止所有运行中任务与后台轮询;先调用stop()则会主动终止任务拉取逻辑,确保Worker彻底清理所有异步资源。
验证步骤
- 将
AppService的disconnect方法替换为上述任一方案 - 重新执行测试:
npm run test - 确认测试完成后Jest正常退出,无报错提示
内容的提问来源于stack exchange,提问作者TheSmartMonkey
相关产品推荐
相关产品推荐

