import { Test, TestingModule } from "@nestjs/testing"; import { DatabaseService } from "../../database/database.service"; import { FavoritesRepository } from "./favorites.repository"; describe("FavoritesRepository", () => { let repository: FavoritesRepository; const mockDb = { select: jest.fn().mockReturnThis(), from: jest.fn().mockReturnThis(), innerJoin: jest.fn().mockReturnThis(), where: jest.fn().mockReturnThis(), limit: jest.fn().mockReturnThis(), offset: jest.fn().mockReturnThis(), insert: jest.fn().mockReturnThis(), values: jest.fn().mockReturnThis(), delete: jest.fn().mockReturnThis(), returning: jest.fn().mockReturnThis(), execute: jest.fn(), }; const wrapWithThen = (obj: unknown) => { // biome-ignore lint/suspicious/noThenProperty: Necessary to mock Drizzle's awaitable query builder Object.defineProperty(obj, "then", { value: function (onFulfilled: (arg0: unknown) => void) { const result = (this as Record).execute(); return Promise.resolve(result).then(onFulfilled); }, configurable: true, }); return obj; }; wrapWithThen(mockDb); beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ FavoritesRepository, { provide: DatabaseService, useValue: { db: mockDb } }, ], }).compile(); repository = module.get(FavoritesRepository); }); it("should find content by id", async () => { (mockDb.execute as jest.Mock).mockResolvedValue([{ id: "1" }]); const result = await repository.findContentById("1"); expect(result.id).toBe("1"); }); it("should add favorite", async () => { (mockDb.execute as jest.Mock).mockResolvedValue([ { userId: "u", contentId: "c" }, ]); await repository.add("u", "c"); expect(mockDb.insert).toHaveBeenCalled(); }); it("should remove favorite", async () => { (mockDb.execute as jest.Mock).mockResolvedValue([{ id: "1" }]); await repository.remove("u", "c"); expect(mockDb.delete).toHaveBeenCalled(); }); it("should find by user id", async () => { (mockDb.execute as jest.Mock).mockResolvedValue([{ content: { id: "c1" } }]); const result = await repository.findByUserId("u1", 10, 0); expect(result).toHaveLength(1); expect(result[0].id).toBe("c1"); }); });