|
| 1 | +import { PrismaService } from '../database/prisma.service'; |
| 2 | +import { SessionsService } from '../sessions/sessions.service'; |
| 3 | +import { AppLogger } from '../common/logger'; |
| 4 | +import { UsersService } from './users.service'; |
| 5 | + |
| 6 | +jest.mock('../auth/security.utils', () => ({ |
| 7 | + ...jest.requireActual('../auth/security.utils'), |
| 8 | + // bcrypt at 12 rounds is slow and irrelevant to what is being tested. |
| 9 | + hashPassword: jest.fn(async (password: string) => `hashed:${password}`), |
| 10 | +})); |
| 11 | + |
| 12 | +type Mock = jest.Mock; |
| 13 | + |
| 14 | +function makePrisma() { |
| 15 | + return { |
| 16 | + user: { |
| 17 | + findUnique: jest.fn(), |
| 18 | + findFirst: jest.fn(), |
| 19 | + findMany: jest.fn(), |
| 20 | + create: jest.fn(), |
| 21 | + update: jest.fn(), |
| 22 | + delete: jest.fn(), |
| 23 | + count: jest.fn(), |
| 24 | + }, |
| 25 | + loginHistory: { findMany: jest.fn() }, |
| 26 | + } as unknown as { user: Record<string, Mock>; loginHistory: Record<string, Mock> }; |
| 27 | +} |
| 28 | + |
| 29 | +describe('UsersService', () => { |
| 30 | + let prisma: ReturnType<typeof makePrisma>; |
| 31 | + let service: UsersService; |
| 32 | + |
| 33 | + beforeEach(() => { |
| 34 | + jest.spyOn(AppLogger.prototype, 'log').mockImplementation(() => undefined); |
| 35 | + jest.spyOn(AppLogger.prototype, 'warn').mockImplementation(() => undefined); |
| 36 | + prisma = makePrisma(); |
| 37 | + service = new UsersService( |
| 38 | + prisma as unknown as PrismaService, |
| 39 | + { revokeAllSessions: jest.fn() } as unknown as SessionsService, |
| 40 | + ); |
| 41 | + }); |
| 42 | + |
| 43 | + afterEach(() => jest.restoreAllMocks()); |
| 44 | + |
| 45 | + describe('create', () => { |
| 46 | + const dto = { |
| 47 | + email: 'new@example.com', |
| 48 | + password: 'Str0ng!Pass', |
| 49 | + firstName: 'Ada', |
| 50 | + lastName: 'Lovelace', |
| 51 | + }; |
| 52 | + |
| 53 | + beforeEach(() => { |
| 54 | + prisma.user.findUnique.mockResolvedValue(null); // referral code is free, no referrer |
| 55 | + prisma.user.create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({ |
| 56 | + id: 'u1', |
| 57 | + ...data, |
| 58 | + twoFactorSecret: 'secret', |
| 59 | + })); |
| 60 | + }); |
| 61 | + |
| 62 | + it('stores a hash, never the plain password, and strips secrets from the result', async () => { |
| 63 | + const result = await service.create(dto); |
| 64 | + |
| 65 | + const data = prisma.user.create.mock.calls[0][0].data; |
| 66 | + expect(data.password).toBe('hashed:Str0ng!Pass'); |
| 67 | + expect(result).not.toHaveProperty('password'); |
| 68 | + expect(result).not.toHaveProperty('twoFactorSecret'); |
| 69 | + expect(result).toMatchObject({ id: 'u1', email: 'new@example.com' }); |
| 70 | + }); |
| 71 | + |
| 72 | + it('seeds password history and default notification preferences', async () => { |
| 73 | + await service.create(dto); |
| 74 | + |
| 75 | + const data = prisma.user.create.mock.calls[0][0].data; |
| 76 | + expect(data.passwordHistory).toEqual({ create: { passwordHash: 'hashed:Str0ng!Pass' } }); |
| 77 | + expect(data.preferences.create).toMatchObject({ |
| 78 | + emailNotifications: true, |
| 79 | + inAppNotifications: true, |
| 80 | + smsNotifications: false, |
| 81 | + }); |
| 82 | + }); |
| 83 | + |
| 84 | + it('generates a 6-character upper-case referral code', async () => { |
| 85 | + await service.create(dto); |
| 86 | + expect(prisma.user.create.mock.calls[0][0].data.referralCode).toMatch(/^[0-9A-Z]{1,6}$/); |
| 87 | + }); |
| 88 | + |
| 89 | + it('retries until the generated referral code is unused', async () => { |
| 90 | + prisma.user.findUnique |
| 91 | + .mockResolvedValueOnce({ id: 'taken' }) // first code collides |
| 92 | + .mockResolvedValueOnce(null); // second is free |
| 93 | + |
| 94 | + await service.create(dto); |
| 95 | + |
| 96 | + expect(prisma.user.findUnique).toHaveBeenCalledTimes(2); |
| 97 | + }); |
| 98 | + |
| 99 | + it('links the new user to the referrer when a valid referral code is given', async () => { |
| 100 | + prisma.user.findUnique |
| 101 | + .mockResolvedValueOnce(null) // generated code is free |
| 102 | + .mockResolvedValueOnce({ id: 'referrer-1' }); // supplied code resolves |
| 103 | + |
| 104 | + await service.create({ ...dto, referralCode: 'FRIEND' }); |
| 105 | + |
| 106 | + expect(prisma.user.findUnique).toHaveBeenLastCalledWith({ where: { referralCode: 'FRIEND' } }); |
| 107 | + expect(prisma.user.create.mock.calls[0][0].data.referredById).toBe('referrer-1'); |
| 108 | + }); |
| 109 | + |
| 110 | + it('ignores an unknown referral code', async () => { |
| 111 | + await service.create({ ...dto, referralCode: 'NOPE' }); |
| 112 | + expect(prisma.user.create.mock.calls[0][0].data.referredById).toBeNull(); |
| 113 | + }); |
| 114 | + }); |
| 115 | + |
| 116 | + describe('lookups', () => { |
| 117 | + it('findOne only returns active users and selects public fields', async () => { |
| 118 | + prisma.user.findFirst.mockResolvedValue({ id: 'u1' }); |
| 119 | + |
| 120 | + await expect(service.findOne('u1')).resolves.toEqual({ id: 'u1' }); |
| 121 | + |
| 122 | + const args = prisma.user.findFirst.mock.calls[0][0]; |
| 123 | + expect(args.where).toEqual({ id: 'u1', isDeactivated: false }); |
| 124 | + expect(args.select).not.toHaveProperty('password'); |
| 125 | + expect(args.select).toMatchObject({ email: true, role: true }); |
| 126 | + }); |
| 127 | + |
| 128 | + it('findOne returns null for an unknown or deactivated user', async () => { |
| 129 | + prisma.user.findFirst.mockResolvedValue(null); |
| 130 | + await expect(service.findOne('missing')).resolves.toBeNull(); |
| 131 | + }); |
| 132 | + |
| 133 | + it('findByEmail looks up by exact email', async () => { |
| 134 | + prisma.user.findUnique.mockResolvedValue({ id: 'u1' }); |
| 135 | + await service.findByEmail('a@example.com'); |
| 136 | + expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { email: 'a@example.com' } }); |
| 137 | + }); |
| 138 | + }); |
| 139 | + |
| 140 | + describe('admin state changes', () => { |
| 141 | + beforeEach(() => { |
| 142 | + prisma.user.update.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => data); |
| 143 | + }); |
| 144 | + |
| 145 | + it('block / unblock toggle isBlocked', async () => { |
| 146 | + await service.block('u1'); |
| 147 | + await service.unblock('u1'); |
| 148 | + |
| 149 | + expect(prisma.user.update.mock.calls[0][0]).toMatchObject({ |
| 150 | + where: { id: 'u1' }, |
| 151 | + data: { isBlocked: true }, |
| 152 | + }); |
| 153 | + expect(prisma.user.update.mock.calls[1][0]).toMatchObject({ data: { isBlocked: false } }); |
| 154 | + }); |
| 155 | + |
| 156 | + it('verify / unverify toggle isVerified and select only id and isVerified', async () => { |
| 157 | + await service.verify('u1'); |
| 158 | + await service.unverify('u1'); |
| 159 | + |
| 160 | + expect(prisma.user.update.mock.calls[0][0]).toMatchObject({ |
| 161 | + data: { isVerified: true }, |
| 162 | + select: { id: true, isVerified: true }, |
| 163 | + }); |
| 164 | + expect(prisma.user.update.mock.calls[1][0]).toMatchObject({ data: { isVerified: false } }); |
| 165 | + }); |
| 166 | + |
| 167 | + it('remove deletes the user', async () => { |
| 168 | + prisma.user.delete.mockResolvedValue({ id: 'u1' }); |
| 169 | + await expect(service.remove('u1')).resolves.toEqual({ id: 'u1' }); |
| 170 | + expect(prisma.user.delete).toHaveBeenCalledWith({ where: { id: 'u1' } }); |
| 171 | + }); |
| 172 | + }); |
| 173 | + |
| 174 | + describe('referrals', () => { |
| 175 | + it('getReferralStats combines the referral code with the referral count', async () => { |
| 176 | + prisma.user.count.mockResolvedValue(3); |
| 177 | + prisma.user.findUnique.mockResolvedValue({ referralCode: 'ABC123' }); |
| 178 | + |
| 179 | + await expect(service.getReferralStats('u1')).resolves.toEqual({ |
| 180 | + referralCode: 'ABC123', |
| 181 | + referralCount: 3, |
| 182 | + }); |
| 183 | + expect(prisma.user.count).toHaveBeenCalledWith({ where: { referredById: 'u1' } }); |
| 184 | + }); |
| 185 | + |
| 186 | + it('getReferralStats tolerates a missing user', async () => { |
| 187 | + prisma.user.count.mockResolvedValue(0); |
| 188 | + prisma.user.findUnique.mockResolvedValue(null); |
| 189 | + await expect(service.getReferralStats('ghost')).resolves.toEqual({ |
| 190 | + referralCode: undefined, |
| 191 | + referralCount: 0, |
| 192 | + }); |
| 193 | + }); |
| 194 | + |
| 195 | + it('getMyReferrals selects only non-sensitive fields', async () => { |
| 196 | + prisma.user.findMany.mockResolvedValue([]); |
| 197 | + await service.getMyReferrals('u1'); |
| 198 | + |
| 199 | + const args = prisma.user.findMany.mock.calls[0][0]; |
| 200 | + expect(args.where).toEqual({ referredById: 'u1' }); |
| 201 | + expect(Object.keys(args.select).sort()).toEqual(['createdAt', 'email', 'firstName', 'id', 'lastName']); |
| 202 | + }); |
| 203 | + }); |
| 204 | + |
| 205 | + describe('getLoginHistory', () => { |
| 206 | + it('returns the caller\'s logins newest first without extra fields', async () => { |
| 207 | + prisma.loginHistory.findMany.mockResolvedValue([{ timestamp: new Date(), ipAddress: '1.1.1.1' }]); |
| 208 | + |
| 209 | + await service.getLoginHistory('u1'); |
| 210 | + |
| 211 | + const args = prisma.loginHistory.findMany.mock.calls[0][0]; |
| 212 | + expect(args.where).toEqual({ userId: 'u1' }); |
| 213 | + expect(args.orderBy).toEqual({ timestamp: 'desc' }); |
| 214 | + expect(args.select).toEqual({ timestamp: true, ipAddress: true, userAgent: true }); |
| 215 | + }); |
| 216 | + }); |
| 217 | +}); |
0 commit comments