You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest与NestJS结合使用时Prisma数据库连接无法正常关闭问题求助

解决方案

1. 修正测试套件中afterAll的执行顺序

你当前的代码是先断开Prisma连接再关闭Nest应用,顺序完全颠倒:Nest应用销毁过程中可能仍有依赖Prisma的服务需要执行清理逻辑,提前断开连接会导致清理流程卡住,Prisma连接无法正常释放。
修改后的afterAll逻辑:

afterAll(async () => {
  await app.close(); // 先关闭Nest应用,完成所有内置服务的销毁流程
  await prismaService.$disconnect(); // 再显式断开Prisma连接
});

2. 测试环境中注册Prisma关闭钩子

你在PrismaService中实现的enableShutdownHooks方法在测试流程中并没有被调用,导致Prisma的生命周期和Nest应用的生命周期没有绑定,关闭时无法触发关联的清理逻辑。
在beforeAll的await app.init()之前补充注册逻辑:

beforeAll(async () => {
  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
    providers: [PrismaService],
  }).compile();

  app = moduleFixture.createNestApplication();
  prismaService = moduleFixture.get(PrismaService);
  prismaService.enableShutdownHooks(app); // 补充这行,绑定两者的生命周期
  await app.init();
});

3. 限制测试环境的Prisma连接池大小

多测试套件并行运行时,每个套件都会初始化独立的PrismaClient实例,很容易打满数据库的最大连接数。你可以在PrismaClient初始化时配置连接池限制:
修改PrismaService的构造函数:

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  constructor() {
    // 测试环境下限制连接池大小为1,生产环境可走默认配置或自定义
    super(process.env.NODE_ENV === 'test' ? { datasources: { db: { url: process.env.DATABASE_URL, connection_limit: 1 } } } : {});
  }

  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}

4. Jest运行配置优化

如果是多测试文件并行执行导致连接数溢出,可以给Jest加上--runInBand参数强制串行执行测试,避免大量Prisma实例同时创建:
在package.json的测试脚本中修改:

{
  "scripts": {
    "test": "jest --runInBand"
  }
}

可选补充:如果仍有超时问题

部分场景下Prisma的pending查询可能会阻塞断开流程,可以在afterAll中加100-200ms的延迟等待所有异步任务清空:

afterAll(async () => {
  await app.close();
  await prismaService.$disconnect();
  await new Promise(resolve => setTimeout(resolve, 100));
});

内容的提问来源于stack exchange,提问作者Brendan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:45:03