import { ConflictException, NotFoundException } from "@nestjs/common"; import { Test, TestingModule } from "@nestjs/testing"; import { FavoritesService } from "./favorites.service"; import { FavoritesRepository } from "./repositories/favorites.repository"; describe("FavoritesService", () => { let service: FavoritesService; let repository: FavoritesRepository; const mockFavoritesRepository = { findContentById: jest.fn(), add: jest.fn(), remove: jest.fn(), findByUserId: jest.fn(), }; beforeEach(async () => { jest.clearAllMocks(); const module: TestingModule = await Test.createTestingModule({ providers: [ FavoritesService, { provide: FavoritesRepository, useValue: mockFavoritesRepository }, ], }).compile(); service = module.get(FavoritesService); repository = module.get(FavoritesRepository); }); it("should be defined", () => { expect(service).toBeDefined(); }); describe("addFavorite", () => { it("should add a favorite", async () => { mockFavoritesRepository.findContentById.mockResolvedValue({ id: "content1", }); mockFavoritesRepository.add.mockResolvedValue([ { userId: "u1", contentId: "content1" }, ]); const result = await service.addFavorite("u1", "content1"); expect(result).toEqual([{ userId: "u1", contentId: "content1" }]); expect(repository.add).toHaveBeenCalledWith("u1", "content1"); }); it("should throw NotFoundException if content does not exist", async () => { mockFavoritesRepository.findContentById.mockResolvedValue(null); await expect(service.addFavorite("u1", "invalid")).rejects.toThrow( NotFoundException, ); }); it("should throw ConflictException on duplicate favorite", async () => { mockFavoritesRepository.findContentById.mockResolvedValue({ id: "content1", }); mockFavoritesRepository.add.mockRejectedValue(new Error("Duplicate")); await expect(service.addFavorite("u1", "content1")).rejects.toThrow( ConflictException, ); }); }); describe("removeFavorite", () => { it("should remove a favorite", async () => { mockFavoritesRepository.remove.mockResolvedValue([ { userId: "u1", contentId: "c1" }, ]); const result = await service.removeFavorite("u1", "c1"); expect(result).toEqual({ userId: "u1", contentId: "c1" }); expect(repository.remove).toHaveBeenCalledWith("u1", "c1"); }); it("should throw NotFoundException if favorite not found", async () => { mockFavoritesRepository.remove.mockResolvedValue([]); await expect(service.removeFavorite("u1", "c1")).rejects.toThrow( NotFoundException, ); }); }); });