Jest 和 NestJs 如何关闭 prisma 连接

Jest and NestJs how how to close the prisma connections

我有一个问题,当我使用 app.close 或 prisma.$disconnect 时,我的测试套件没有关闭与 prisma 的连接。这意味着我 运行 在 运行 我的测试套件时遇到错误。

Error querying the database: db error: FATAL: sorry, too many clients already

以及

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.

这是我的典型测试套件的蓝图:

import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { AppModule } from '../../src/app.module';
import { PrismaService } from '../../src/prisma.service';

describe('Description', () => {
  let app: INestApplication;
  let prismaService: PrismaService;

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

    app = moduleFixture.createNestApplication();
    prismaService = moduleFixture.get(PrismaService);
    await app.init();
  });

  afterAll(async () => {
    await prismaService.$disconnect();
    await app.close();
  });

  it('Should do something', async () => {
    expect(1).toEqual(1);
  });
});

我对 Prisma 服务的实现

import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }

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

我之前使用的是 TypeOrm,app.close() 解决了这个问题,但是在转向 prisma 之后,我无法解决这个问题。

任何帮助将不胜感激。谢谢

您可以查看 this issue,其中讨论了各种上下文(包括测试、无服务器环境等)中的连接问题。

一种解决方法(适用于此问题的原始发布者)是通过将 ?connection_limit=1 附加到连接字符串来手动设置连接限制。

更新到 Prisma 的最新主要版本已经解决了这个问题。就我而言,我现在使用的确切版本是 3.4.2.