import { Test, TestingModule } from "@nestjs/testing"; import { CategoriesService } from "./categories.service"; import { PrismaService } from "../prisma/prisma.service"; import { NotFoundException } from "@nestjs/common"; describe("CategoriesService", () => { let service: CategoriesService; const mockPrisma = { category: { upsert: jest.fn(), findMany: jest.fn(), count: jest.fn(), findUnique: jest.fn(), create: jest.fn(), update: jest.fn(), delete: jest.fn(), }, product: { updateMany: jest.fn(), }, }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ CategoriesService, { provide: PrismaService, useValue: mockPrisma }, ], }).compile(); service = module.get(CategoriesService); jest.clearAllMocks(); }); it("should be defined", () => { expect(service).toBeDefined(); }); describe("getCategories", () => { it("should paginate and filter categories by search term", async () => { const mockCats = [{ id: "cat-1", name: "مفاصل و استخوان" }]; mockPrisma.category.findMany.mockResolvedValue(mockCats); mockPrisma.category.count.mockResolvedValue(1); const res = await service.getCategories({ search: "مفاصل", page: 1, limit: 10, }); expect(mockPrisma.category.findMany).toHaveBeenCalledWith({ where: { name: { contains: "مفاصل", mode: "insensitive" } }, skip: 0, take: 10, orderBy: { createdAt: "desc" }, }); expect(res.data).toEqual(mockCats); expect(res.meta.total).toBe(1); }); }); describe("createCategory", () => { it("should auto-generate slug if slug is omitted", async () => { mockPrisma.category.create.mockResolvedValue({ id: "cat-2", name: "تقویت پوست", slug: "تقویت-پوست", }); await service.createCategory({ name: "تقویت پوست", } as any); expect(mockPrisma.category.create).toHaveBeenCalledWith({ data: expect.objectContaining({ name: "تقویت پوست", slug: "تقویت-پوست", }), }); }); }); describe("updateCategory and deleteCategory", () => { it("should throw NotFoundException on update if category not found", async () => { mockPrisma.category.findUnique.mockResolvedValue(null); await expect( service.updateCategory("cat-404", { name: "نام جدید" }), ).rejects.toThrow(NotFoundException); }); it("should throw NotFoundException on delete if category not found", async () => { mockPrisma.category.findUnique.mockResolvedValue(null); await expect(service.deleteCategory("cat-404")).rejects.toThrow( NotFoundException, ); }); it("should delete category when found", async () => { mockPrisma.category.findUnique.mockResolvedValue({ id: "cat-1" }); mockPrisma.category.delete.mockResolvedValue({ id: "cat-1" }); const res = await service.deleteCategory("cat-1"); expect(res.id).toBe("cat-1"); }); }); });