From f81f51e508d856c8da93f00c3c848d6060016502 Mon Sep 17 00:00:00 2001 From: mzaxd Date: Tue, 27 Jan 2026 21:37:34 +0800 Subject: [PATCH] test: add API route tests --- src/app/api/events/route.test.ts | 78 ++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/app/api/events/route.test.ts diff --git a/src/app/api/events/route.test.ts b/src/app/api/events/route.test.ts new file mode 100644 index 0000000..1c567a5 --- /dev/null +++ b/src/app/api/events/route.test.ts @@ -0,0 +1,78 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { POST, GET } from './route'; +import { NextRequest } from 'next/server'; + +describe('POST /api/events', () => { + const validEvent = { + title: 'GPT-4 发布', + eventDate: '2023-03-14T00:00:00Z', + description: 'OpenAI 发布多模态大语言模型', + imageUrl: 'https://example.com/gpt4.jpg', + }; + + it('should reject without API key', async () => { + const request = new NextRequest('http://localhost:3000/api/events', { + method: 'POST', + body: JSON.stringify([validEvent]), + }); + + const response = await POST(request); + expect(response.status).toBe(401); + + const json = await response.json(); + expect(json.error).toBe('Unauthorized'); + }); + + it('should reject with invalid API key', async () => { + const request = new NextRequest('http://localhost:3000/api/events', { + method: 'POST', + headers: { + 'X-API-Key': 'invalid-key', + }, + body: JSON.stringify([validEvent]), + }); + + const response = await POST(request); + expect(response.status).toBe(401); + }); + + // 注意: 以下测试需要设置 WEBHOOK_API_KEY 环境变量 + // 可以通过 vi.stubEnv 来模拟 +}); + +describe('GET /api/events', () => { + it('should return events array', async () => { + const request = new NextRequest('http://localhost:3000/api/events'); + const response = await GET(request); + + expect(response.status).toBe(200); + + const json = await response.json(); + expect(json).toHaveProperty('events'); + expect(Array.isArray(json.events)).toBe(true); + }); + + it('should filter by year', async () => { + const request = new NextRequest( + 'http://localhost:3000/api/events?year=2024' + ); + const response = await GET(request); + + expect(response.status).toBe(200); + + const json = await response.json(); + expect(json).toHaveProperty('events'); + }); + + it('should reject invalid year format', async () => { + const request = new NextRequest( + 'http://localhost:3000/api/events?year=invalid' + ); + const response = await GET(request); + + expect(response.status).toBe(400); + + const json = await response.json(); + expect(json.error).toBe('Invalid query parameters'); + }); +});