0

I am working in a NestJS project and had a question about that.

I'm not that fluent yet in writing unit test cases, I have written some generic ones for my controllers such as users.controller.spec.ts and for the services users.service.spec.ts. I was wondering, how would I go about writing the test file for the prisma.service.spec.ts? I have a prisma.service.ts file that looks like this:

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

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  constructor(config: ConfigService) {
    super({
      datasources: {
        db: {
          url: config.get<string>('DATABASE_URL'),
        },
      },
    });
  }

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

  async onModuleDestroy() {
    await this.$disconnect();
  }

  async cleanDatabase() {
    if (process.env.NODE_ENV === 'production') return;
    const models = Reflect.ownKeys(this).filter((key) => key[0] !== '_');

    return Promise.all(models.map((modelKey) => this[modelKey].deleteMany()));
  }
}

And NestJS CLI generates this generic spec.ts file when you create a service that looks like this:

import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from './prisma.service';

describe('PrismaService', () => {
  let service: PrismaService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [PrismaService],
    }).compile();

    service = module.get<PrismaService>(PrismaService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});
some-user
  • 3,888
  • 5
  • 19
  • 43
  • There is a related Stack Overflow question which answers the same question: https://stackoverflow.com/questions/70228893/testing-a-nestjs-service-that-uses-prisma-without-actually-accessing-the-databas This reddit link should also be helpful to you: https://www.reddit.com/r/Nestjs_framework/comments/w8p5wo/testing_in_nestjs_with_prisma/ – Nurul Sundarani Oct 21 '22 at 12:32
  • These are not related with the question. The answers you shared are for testing other services using prisma service. This question is about how to test prisma service itself. – Mansur Jun 02 '23 at 23:35

0 Answers0