jestjsnestjsprisma

Prisma is opening too many connections with PostgrsQL when running Jest end to end testing


I'm trying here to do end to end testing with Jest on a NestJS/GraphQL app and Prisma as my ORM.

What happens here is Prisma is opening too many connections with Postgres, I've tried to fix this problem by using prisma.$disconnect() after each test but it doesn't seem to work...

This is what I've tried so far.

import { PrismaService } from '../src/prisma.service';

describe('Users', () => {
  let app: INestApplication;
  const gql = '/graphql';
  let prisma;

  beforeEach(async () => {
    prisma = new PrismaService();

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

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  afterEach(async () => {
    await prisma.$disconnect();
  });

  it('Query - Users', async () => {
    //Using prisma to query database
  });
});

My Prisma service (I got it from NestJS documentation Text ):

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();
    });
  }
}

These are the errors I'm getting after running all the tests (serially):

enter image description here

I've already looked through Prisma documentation but didn't find anything about how to setup properly a Jest environment with NestJS and Prisma.

Thanks for your help !


Solution

  • Explicitly instructing Prisma to open only one connection with your database should solve this issue.

    You can do it by appending connection_limit=1 to your connection string.

    Demo Connection String:

    postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public&connection_limit=1
    

    Reference to connection management in prisma should be helpful as well.