import { describe, it, expect, vi, beforeEach } from "vitest"; import AccountRepository from "../src/domain/account/repository/AccoutRepository"; import { DatabaseInterface } from "../src/database/DatabaseInterface"; import { AccountEntity } from "../src/domain/account/entity/AccountEntity"; describe("AccountRepository", () => { let accountRepository: AccountRepository; let mockDatabase: DatabaseInterface; beforeEach(() => { mockDatabase = { ping: vi.fn(), fetchAll: vi.fn(), fetchOne: vi.fn(), execute: vi.fn(), }; accountRepository = new AccountRepository(mockDatabase); }); describe("findByEmail", () => { it("should return account when found", async () => { const email = "test@example.com"; const mockResult = { id: "123", email: email, password: "hashedPassword", role_id: 1, created_at: new Date(), updated_at: new Date(), }; vi.mocked(mockDatabase.fetchOne).mockResolvedValue(mockResult); const result = await accountRepository.findByEmail(email); expect(result).toBeInstanceOf(AccountEntity); expect(result?.email).toBe(email); expect(mockDatabase.fetchOne).toHaveBeenCalledWith( expect.stringContaining( "SELECT id, email, password, role_id, created_at, updated_at", ), [email], ); }); it("should return null when account not found", async () => { const email = "nonexistent@example.com"; vi.mocked(mockDatabase.fetchOne).mockResolvedValue(undefined); const result = await accountRepository.findByEmail(email); expect(result).toBeNull(); }); }); describe("findById", () => { it("should return account when found", async () => { const id = "123"; const mockResult = { id: id, email: "test@example.com", password: "hashedPassword", role_id: 1, created_at: new Date(), updated_at: new Date(), }; vi.mocked(mockDatabase.fetchOne).mockResolvedValue(mockResult); const result = await accountRepository.findById(id); expect(result).toBeInstanceOf(AccountEntity); expect(result?.id).toBe(id); expect(mockDatabase.fetchOne).toHaveBeenCalledWith( expect.stringContaining( "SELECT id, email, password, role_id, created_at, updated_at", ), [id], ); }); it("should return null when account not found", async () => { const id = "nonexistent"; vi.mocked(mockDatabase.fetchOne).mockResolvedValue(undefined); const result = await accountRepository.findById(id); expect(result).toBeNull(); }); }); describe("save", () => { it("should save account successfully", async () => { const account = AccountEntity.create("test@example.com", "password123"); vi.mocked(mockDatabase.fetchOne).mockResolvedValue({ id: account.id }); const result = await accountRepository.save(account); expect(result).toBe(account.id); expect(mockDatabase.fetchOne).toHaveBeenCalledWith( expect.stringContaining("INSERT INTO accounts"), expect.arrayContaining([ account.id, account.email, expect.any(String), account.roleId, account.createdAt, account.updatedAt, ]), ); }); }); });