b207bfa7af
test: 添加单元测试和端到端测试 refactor: 重构登录页面和上传模块 ci: 更新测试覆盖率阈值至42% build: 添加测试相关依赖 docs: 更新测试文档 style: 修复代码格式问题
99 lines
2.8 KiB
TypeScript
99 lines
2.8 KiB
TypeScript
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('未授权');
|
|
});
|
|
});
|
|
});
|