|
| 1 | +jest.mock('$lib/server/prisma/users/service', () => ({ deleteUser: jest.fn() })); |
| 2 | +jest.mock('$lib/server/auth/services', () => ({ logout: jest.fn() })); |
| 3 | +jest.mock('$lib/utils', () => ({ isAdmin: jest.fn(() => false) })); |
| 4 | + |
| 5 | +import { t } from './t'; |
| 6 | +import { deleteAccount } from './procedures/deleteAccount'; |
| 7 | +import { deleteUser } from '$lib/server/prisma/users/service'; |
| 8 | +import { logout } from '$lib/server/auth/services'; |
| 9 | +import { isAdmin } from '$lib/utils'; |
| 10 | +import { makeCaller, mockUser, mockCookies } from './test-utils'; |
| 11 | + |
| 12 | +const mockDeleteUser = jest.mocked(deleteUser); |
| 13 | +const mockLogout = jest.mocked(logout); |
| 14 | +const mockIsAdmin = jest.mocked(isAdmin); |
| 15 | + |
| 16 | +const router = t.router({ deleteAccount }); |
| 17 | +const createCaller = t.createCallerFactory(router); |
| 18 | + |
| 19 | +beforeEach(() => jest.clearAllMocks()); |
| 20 | + |
| 21 | +describe('deleteAccount', () => { |
| 22 | + it('deletes the authenticated user and clears the session', async () => { |
| 23 | + await makeCaller(createCaller, mockUser).deleteAccount(); |
| 24 | + |
| 25 | + expect(mockDeleteUser).toHaveBeenCalledTimes(1); |
| 26 | + expect(mockDeleteUser).toHaveBeenCalledWith(mockUser.id); |
| 27 | + expect(mockLogout).toHaveBeenCalledWith(mockCookies); |
| 28 | + }); |
| 29 | + |
| 30 | + it('can only delete the authenticated user — no input means no other target is possible', async () => { |
| 31 | + const anotherUser = { ...mockUser, id: 999, username: 'anotheruser' }; |
| 32 | + |
| 33 | + await makeCaller(createCaller, anotherUser).deleteAccount(); |
| 34 | + |
| 35 | + expect(mockDeleteUser).toHaveBeenCalledWith(anotherUser.id); |
| 36 | + expect(mockDeleteUser).not.toHaveBeenCalledWith(mockUser.id); |
| 37 | + expect(mockLogout).toHaveBeenCalledWith(mockCookies); |
| 38 | + }); |
| 39 | + |
| 40 | + it('throws UNAUTHORIZED and skips deletion when not authenticated', async () => { |
| 41 | + await expect(makeCaller(createCaller, null).deleteAccount()).rejects.toMatchObject({ |
| 42 | + code: 'UNAUTHORIZED', |
| 43 | + }); |
| 44 | + |
| 45 | + expect(mockDeleteUser).not.toHaveBeenCalled(); |
| 46 | + expect(mockLogout).not.toHaveBeenCalled(); |
| 47 | + }); |
| 48 | + |
| 49 | + it('throws FORBIDDEN and skips deletion for admin accounts', async () => { |
| 50 | + mockIsAdmin.mockReturnValue(true); |
| 51 | + |
| 52 | + await expect(makeCaller(createCaller, mockUser).deleteAccount()).rejects.toMatchObject({ |
| 53 | + code: 'FORBIDDEN', |
| 54 | + }); |
| 55 | + |
| 56 | + expect(mockDeleteUser).not.toHaveBeenCalled(); |
| 57 | + expect(mockLogout).not.toHaveBeenCalled(); |
| 58 | + }); |
| 59 | +}); |
0 commit comments