|
| 1 | +/** |
| 2 | + * Unit tests for the password helper (bcrypt wrappers). |
| 3 | + * Dependency-free leaf — mocks only bcrypt. |
| 4 | + */ |
| 5 | +import { jest, describe, test, expect, beforeEach } from '@jest/globals'; |
| 6 | + |
| 7 | +const mockBcryptHash = jest.fn(); |
| 8 | +const mockBcryptCompare = jest.fn(); |
| 9 | + |
| 10 | +jest.unstable_mockModule('bcrypt', () => ({ |
| 11 | + default: { |
| 12 | + hash: (...args) => mockBcryptHash(...args), |
| 13 | + compare: (...args) => mockBcryptCompare(...args), |
| 14 | + }, |
| 15 | +})); |
| 16 | + |
| 17 | +const { default: passwordHelper, hashPassword, comparePassword } = await import('../password.js'); |
| 18 | + |
| 19 | +describe('password helper', () => { |
| 20 | + beforeEach(() => { |
| 21 | + mockBcryptHash.mockReset(); |
| 22 | + mockBcryptCompare.mockReset(); |
| 23 | + }); |
| 24 | + |
| 25 | + describe('hashPassword()', () => { |
| 26 | + test('hashes the stringified password with saltRounds = 10', async () => { |
| 27 | + mockBcryptHash.mockResolvedValueOnce('$2b$hashed'); |
| 28 | + const result = await hashPassword('mypassword'); |
| 29 | + expect(result).toBe('$2b$hashed'); |
| 30 | + expect(mockBcryptHash).toHaveBeenCalledWith('mypassword', 10); |
| 31 | + }); |
| 32 | + |
| 33 | + test('coerces a non-string password to a string before hashing', async () => { |
| 34 | + mockBcryptHash.mockResolvedValueOnce('$2b$num'); |
| 35 | + await hashPassword(12345); |
| 36 | + expect(mockBcryptHash).toHaveBeenCalledWith('12345', 10); |
| 37 | + }); |
| 38 | + }); |
| 39 | + |
| 40 | + describe('comparePassword()', () => { |
| 41 | + test('compares the stringified candidate against the stored hash', async () => { |
| 42 | + mockBcryptCompare.mockResolvedValueOnce(true); |
| 43 | + const result = await comparePassword('plain', 'hashed'); |
| 44 | + expect(result).toBe(true); |
| 45 | + expect(mockBcryptCompare).toHaveBeenCalledWith('plain', 'hashed'); |
| 46 | + }); |
| 47 | + |
| 48 | + test('coerces non-string args to strings before comparing', async () => { |
| 49 | + mockBcryptCompare.mockResolvedValueOnce(false); |
| 50 | + await comparePassword(12345, 67890); |
| 51 | + expect(mockBcryptCompare).toHaveBeenCalledWith('12345', '67890'); |
| 52 | + }); |
| 53 | + |
| 54 | + test('returns false when the candidate does not match the stored hash', async () => { |
| 55 | + mockBcryptCompare.mockResolvedValueOnce(false); |
| 56 | + const result = await comparePassword('wrong', 'hashed'); |
| 57 | + expect(result).toBe(false); |
| 58 | + }); |
| 59 | + }); |
| 60 | + |
| 61 | + describe('default export', () => { |
| 62 | + test('exposes hashPassword and comparePassword', () => { |
| 63 | + expect(typeof passwordHelper.hashPassword).toBe('function'); |
| 64 | + expect(typeof passwordHelper.comparePassword).toBe('function'); |
| 65 | + }); |
| 66 | + }); |
| 67 | +}); |
0 commit comments