test: 添加完整测试套件(52 个文件,326 个用例)
基于 Vitest 搭建测试基础设施,覆盖后端纯函数、API 路由、 前端 hooks、UI 组件和页面级集成测试。
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { createRequest, parseJsonResponse } from "@/__tests__/helpers/api-test-utils";
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({ prisma: {} }));
|
||||
|
||||
vi.mock("@/lib/amap", () => ({
|
||||
requireAmapApiKey: vi.fn().mockReturnValue("test-key"),
|
||||
}));
|
||||
|
||||
const mockFetch = vi.fn();
|
||||
vi.stubGlobal("fetch", mockFetch);
|
||||
|
||||
import { GET } from "./route";
|
||||
|
||||
const mockCtx = { params: Promise.resolve({}) };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("GET /api/location/regeo", () => {
|
||||
it("returns reverse geocoded location", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
status: "1",
|
||||
regeocode: {
|
||||
formatted_address: "上海市黄浦区人民大道",
|
||||
addressComponent: {
|
||||
district: "黄浦区",
|
||||
township: "南京东路街道",
|
||||
neighborhood: { name: "人民广场" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const req = createRequest("/api/location/regeo?lat=31.23&lng=121.47");
|
||||
const res = await GET(req, mockCtx);
|
||||
const { status, data } = await parseJsonResponse(res);
|
||||
|
||||
expect(status).toBe(200);
|
||||
expect(data.name).toContain("黄浦区");
|
||||
expect(data.formatted).toBe("上海市黄浦区人民大道");
|
||||
});
|
||||
|
||||
it("returns null name when API returns no result", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
json: () => Promise.resolve({ status: "0" }),
|
||||
});
|
||||
|
||||
const req = createRequest("/api/location/regeo?lat=31.23&lng=121.47");
|
||||
const res = await GET(req, mockCtx);
|
||||
const { data } = await parseJsonResponse(res);
|
||||
expect(data.name).toBeNull();
|
||||
});
|
||||
|
||||
it("returns 400 when coordinates missing", async () => {
|
||||
const req = createRequest("/api/location/regeo");
|
||||
const res = await GET(req, mockCtx);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 503 when API unavailable", async () => {
|
||||
mockFetch.mockRejectedValue(new Error("network"));
|
||||
|
||||
const req = createRequest("/api/location/regeo?lat=31.23&lng=121.47");
|
||||
const res = await GET(req, mockCtx);
|
||||
expect(res.status).toBe(503);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user