import { GET, POST } from './route' import { getServerSession } from 'next-auth' import { prisma } from '@/lib/prisma' import bcrypt from 'bcryptjs' jest.mock('next-auth') jest.mock('@/lib/prisma', () => ({ prisma: { user: { findMany: jest.fn(), create: jest.fn() } } })) jest.mock('bcryptjs') const mockSession = getServerSession as jest.MockedFunction const mockFindMany = prisma.user.findMany as jest.MockedFunction const mockCreate = prisma.user.create as jest.MockedFunction const mockHash = bcrypt.hash as jest.MockedFunction const adminSession = { user: { id: 'admin-id', role: 'admin' } } const gestSession = { user: { id: 'gest-id', role: 'gestionnaire' } } describe('GET /api/admin/users', () => { it('retourne 403 si non admin', async () => { mockSession.mockResolvedValue(gestSession as never) const res = await GET(new Request('http://localhost') as never) expect(res.status).toBe(403) }) it('retourne la liste des utilisateurs', async () => { mockSession.mockResolvedValue(adminSession as never) mockFindMany.mockResolvedValue([ { id: '1', email: 'a@b.com', name: 'Alice', role: 'admin', createdAt: new Date() } as never, ]) const res = await GET(new Request('http://localhost') as never) const body = await res.json() expect(body).toHaveLength(1) expect(body[0].email).toBe('a@b.com') expect(body[0].password).toBeUndefined() }) }) describe('POST /api/admin/users', () => { it('retourne 403 si non admin', async () => { mockSession.mockResolvedValue(gestSession as never) const res = await POST(new Request('http://localhost', { method: 'POST', body: '{}' }) as never) expect(res.status).toBe(403) }) it('crée un utilisateur avec mot de passe hashé', async () => { mockSession.mockResolvedValue(adminSession as never) mockHash.mockResolvedValue('hashed' as never) mockCreate.mockResolvedValue({ id: 'new', email: 'b@c.com', name: 'Bob', role: 'gestionnaire', createdAt: new Date() } as never) const body = JSON.stringify({ email: 'b@c.com', name: 'Bob', password: 'pass123', role: 'gestionnaire' }) const res = await POST(new Request('http://localhost', { method: 'POST', body, headers: { 'Content-Type': 'application/json' } }) as never) expect(res.status).toBe(201) expect(mockHash).toHaveBeenCalledWith('pass123', 12) }) it('retourne 400 si champs manquants', async () => { mockSession.mockResolvedValue(adminSession as never) const body = JSON.stringify({ email: 'b@c.com' }) const res = await POST(new Request('http://localhost', { method: 'POST', body, headers: { 'Content-Type': 'application/json' } }) as never) expect(res.status).toBe(400) }) })