user.entity.test.ts71 lines, 1.9 KB
| 1 | import { User } from "../../entities/user.entity"; |
| 2 | import * as bcrypt from "bcrypt"; |
| 3 | |
| 4 | // Mock bcrypt |
| 5 | jest.mock("bcrypt"); |
| 6 | |
| 7 | describe("User Entity", () => { |
| 8 | let user: User; |
| 9 | |
| 10 | beforeEach(() => { |
| 11 | user = new User(); |
| 12 | user.email = "test@example.com"; |
| 13 | user.password = "password123"; |
| 14 | user.name = "Test User"; |
| 15 | |
| 16 | jest.clearAllMocks(); |
| 17 | |
| 18 | // Mock bcrypt hash and compare methods |
| 19 | (bcrypt.hash as jest.Mock).mockResolvedValue("hashed_password"); |
| 20 | (bcrypt.compare as jest.Mock).mockResolvedValue(true); |
| 21 | }); |
| 22 | |
| 23 | describe("hashPassword", () => { |
| 24 | it("should hash password before insert", async () => { |
| 25 | // Execute |
| 26 | await user.hashPassword(); |
| 27 | |
| 28 | // Assert |
| 29 | expect(bcrypt.hash).toHaveBeenCalledWith("password123", 10); |
| 30 | expect(user.password).toBe("hashed_password"); |
| 31 | }); |
| 32 | |
| 33 | it("should not hash password if already hashed (length >= 60)", async () => { |
| 34 | // Setup - create a user with an already hashed password (long string) |
| 35 | user.password = "a".repeat(60); |
| 36 | |
| 37 | // Execute |
| 38 | await user.hashPassword(); |
| 39 | |
| 40 | // Assert |
| 41 | expect(bcrypt.hash).not.toHaveBeenCalled(); |
| 42 | expect(user.password).toBe("a".repeat(60)); |
| 43 | }); |
| 44 | }); |
| 45 | |
| 46 | describe("comparePassword", () => { |
| 47 | it("should return true for matching password", async () => { |
| 48 | // Execute |
| 49 | const result = await user.comparePassword("password123"); |
| 50 | |
| 51 | // Assert |
| 52 | expect(bcrypt.compare).toHaveBeenCalledWith("password123", user.password); |
| 53 | expect(result).toBe(true); |
| 54 | }); |
| 55 | |
| 56 | it("should return false for non-matching password", async () => { |
| 57 | // Setup |
| 58 | (bcrypt.compare as jest.Mock).mockResolvedValueOnce(false); |
| 59 | |
| 60 | // Execute |
| 61 | const result = await user.comparePassword("wrong_password"); |
| 62 | |
| 63 | // Assert |
| 64 | expect(bcrypt.compare).toHaveBeenCalledWith( |
| 65 | "wrong_password", |
| 66 | user.password |
| 67 | ); |
| 68 | expect(result).toBe(false); |
| 69 | }); |
| 70 | }); |
| 71 | }); |