test: 添加完整测试套件(52 个文件,326 个用例)
基于 Vitest 搭建测试基础设施,覆盖后端纯函数、API 路由、 前端 hooks、UI 组件和页面级集成测试。
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { ToastContext, type ToastContextValue } from "@/hooks/useToast";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
push: vi.fn(),
|
||||
back: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/userId", () => ({
|
||||
getUserId: vi.fn().mockReturnValue("user-1"),
|
||||
getCachedProfile: vi.fn().mockReturnValue({ id: "user-1", username: "testuser", avatar: "🐱" }),
|
||||
setCachedProfile: vi.fn(),
|
||||
setCachedPreferences: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/avatars", () => ({
|
||||
getAvatarBg: vi.fn().mockReturnValue("bg-amber-100"),
|
||||
AVATARS: [
|
||||
{ emoji: "🐱", bg: "bg-amber-100" },
|
||||
{ emoji: "🐶", bg: "bg-orange-100" },
|
||||
],
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ProfileFavoritesCard", () => ({
|
||||
default: () => <div data-testid="favorites-card" />,
|
||||
}));
|
||||
|
||||
const mockFetch = vi.fn();
|
||||
vi.stubGlobal("fetch", mockFetch);
|
||||
|
||||
import ProfilePage from "./page";
|
||||
|
||||
const toastCtx: ToastContextValue = { show: vi.fn() };
|
||||
|
||||
function renderPage() {
|
||||
return render(
|
||||
React.createElement(
|
||||
ToastContext.Provider,
|
||||
{ value: toastCtx },
|
||||
React.createElement(ProfilePage),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
id: "user-1",
|
||||
username: "testuser",
|
||||
avatar: "🐱",
|
||||
email: null,
|
||||
achievements: {
|
||||
totalDecisions: 5,
|
||||
unanimousCount: 2,
|
||||
roomsCreated: 3,
|
||||
streak: 1,
|
||||
},
|
||||
records: [],
|
||||
favorites: [],
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
describe("ProfilePage", () => {
|
||||
it("renders profile heading", () => {
|
||||
renderPage();
|
||||
expect(screen.getByText("个人中心")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("fetches user profile data with correct URL", async () => {
|
||||
renderPage();
|
||||
await waitFor(() => {
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"/api/user?id=user-1",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("renders user info after data loads", async () => {
|
||||
renderPage();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("testuser")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders navigation element", () => {
|
||||
renderPage();
|
||||
expect(screen.getByRole("navigation")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user