import { POST, DELETE } from './route'; import { NextRequest } from 'next/server'; jest.mock('@/lib/auth', () => ({ auth: jest.fn(), })); jest.mock('@/lib/auth/permissions', () => ({ hasPermission: jest.fn(), })); jest.mock('@/lib/audit', () => ({ createAuditLog: jest.fn(), })); jest.mock('@/lib/upload', () => ({ uploadFile: jest.fn().mockResolvedValue({ id: 'test-id', name: 'test.jpg', type: 'image', size: 1024, url: 'https://example.com/test.jpg', }), deleteFile: jest.fn(), })); describe('/api/admin/upload', () => { beforeEach(() => { jest.clearAllMocks(); }); describe('POST', () => { it('should return 401 if not authenticated', async () => { const formData = new FormData(); formData.append('file', new File(['test'], 'test.jpg', { type: 'image/jpeg' })); const request = new NextRequest('http://localhost/api/admin/upload', { method: 'POST', body: formData, }); const response = await POST(request); const data = await response.json(); expect(response.status).toBe(401); expect(data.error).toBe('未授权'); }); it('should return 403 if no permission', async () => { const { auth } = require('@/lib/auth'); const { hasPermission } = require('@/lib/auth/permissions'); auth.mockResolvedValue({ user: { role: 'viewer' } }); hasPermission.mockReturnValue(false); const request = new NextRequest('http://localhost/api/admin/upload', { method: 'POST', }); const response = await POST(request); const data = await response.json(); expect(response.status).toBe(403); expect(data.error).toBe('无权限'); }); it('should return 400 if no file', async () => { const { auth } = require('@/lib/auth'); const { hasPermission } = require('@/lib/auth/permissions'); auth.mockResolvedValue({ user: { role: 'admin', id: 'test-user' } }); hasPermission.mockReturnValue(true); const request = { formData: jest.fn().mockResolvedValue(new FormData()), } as any; const response = await POST(request); const data = await response.json(); expect(response.status).toBe(400); expect(data.error).toBe('未找到文件'); }); }); describe('DELETE', () => { it('should return 401 if not authenticated', async () => { const { auth } = require('@/lib/auth'); auth.mockResolvedValue(null); const request = new NextRequest('http://localhost/api/admin/upload?url=test.jpg', { method: 'DELETE', }); const response = await DELETE(request); const data = await response.json(); expect(response.status).toBe(401); expect(data.error).toBe('未授权'); }); }); });