Unit Tests with TestingModule

Testing ProductsService

src/products/products.service.spec.ts

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

describe('ProductsService', () => {
  let service: ProductsService;
  const prisma = {
    product: { findUnique: jest.fn(), create: jest.fn(), update: jest.fn() },
  };

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

    service = module.get(ProductsService);
    jest.clearAllMocks();
  });

  it('returns the product when it exists', async () => {
    prisma.product.findUnique.mockResolvedValue({ id: 7, name: 'boAt Airdopes 141', price: 1299 });
    await expect(service.findOne(7)).resolves.toMatchObject({ id: 7 });
    expect(prisma.product.findUnique).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 7 } }));
  });

  it('throws NotFoundException when the product is missing', async () => {
    prisma.product.findUnique.mockResolvedValue(null);
    await expect(service.findOne(99)).rejects.toThrow(NotFoundException);
  });
});

Example

npm test -- products.service

Example output

 PASS  src/products/products.service.spec.ts
  ProductsService
    ✓ returns the product when it exists (6 ms)
    ✓ throws NotFoundException when the product is missing (2 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.84 s