geo/frontend/__tests__/lib/api/suggestions.test.ts

109 lines
3.0 KiB
TypeScript

/**
* Suggestions API 路径测试
*
* 验证前端 API 路径与后端路由一致
* 后端路由: /api/v1/brands/${brandId}/suggestions/*
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { suggestionsApi } from "@/lib/api/suggestions";
import { API_BASE } from "@/lib/api/client";
const mockFetch = vi.fn();
const originalFetch = global.fetch;
beforeEach(() => {
global.fetch = mockFetch;
vi.clearAllMocks();
mockFetch.mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve([]),
});
});
afterEach(() => {
global.fetch = originalFetch;
});
function getCalledUrl() {
return mockFetch.mock.calls[0][0] as string;
}
function getCalledMethod() {
return mockFetch.mock.calls[0][1]?.method as string;
}
describe("suggestionsApi 路径测试", () => {
describe("getSuggestions", () => {
it("应使用正确的路径 /api/v1/brands/${brandId}/suggestions", async () => {
await suggestionsApi.getSuggestions("token-123", "brand-abc");
const url = getCalledUrl();
expect(url).toBe(`${API_BASE}/api/v1/brands/brand-abc/suggestions`);
});
it("应正确传递查询参数", async () => {
await suggestionsApi.getSuggestions("token-123", "brand-abc", {
status: "pending",
page: 1,
});
const url = getCalledUrl();
expect(url).toContain(`${API_BASE}/api/v1/brands/brand-abc/suggestions`);
expect(url).toContain("status=pending");
expect(url).toContain("page=1");
});
it("空参数时不应包含查询字符串", async () => {
await suggestionsApi.getSuggestions("token-123", "brand-abc", {});
const url = getCalledUrl();
expect(url).toBe(`${API_BASE}/api/v1/brands/brand-abc/suggestions`);
});
});
describe("regenerateSuggestions", () => {
it("应使用正确的路径 /api/v1/brands/${brandId}/suggestions/regenerate", async () => {
await suggestionsApi.regenerateSuggestions("token-123", "brand-abc");
const url = getCalledUrl();
const method = getCalledMethod();
expect(url).toBe(`${API_BASE}/api/v1/brands/brand-abc/suggestions/regenerate`);
expect(method).toBe("POST");
});
});
describe("updateSuggestionStatus", () => {
it("应使用正确的路径 /api/v1/brands/${brandId}/suggestions/${suggestionId}/status", async () => {
await suggestionsApi.updateSuggestionStatus(
"token-123",
"brand-abc",
"suggestion-xyz",
"completed"
);
const url = getCalledUrl();
const method = getCalledMethod();
expect(url).toBe(
`${API_BASE}/api/v1/brands/brand-abc/suggestions/suggestion-xyz/status`
);
expect(method).toBe("PUT");
});
it("应正确传递状态数据", async () => {
await suggestionsApi.updateSuggestionStatus(
"token-123",
"brand-abc",
"suggestion-xyz",
"completed"
);
const options = mockFetch.mock.calls[0][1];
expect(JSON.parse(options.body)).toEqual({ status: "completed" });
});
});
});