3ccd1262f9
基于 Vitest 搭建测试基础设施,覆盖后端纯函数、API 路由、 前端 hooks、UI 组件和页面级集成测试。
72 lines
2.2 KiB
TypeScript
72 lines
2.2 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import { prismaMock, resetPrismaMock } from "@/__tests__/helpers/prisma-mock";
|
|
import { createRequest, parseJsonResponse } from "@/__tests__/helpers/api-test-utils";
|
|
import { TEST_USER } from "@/__tests__/helpers/fixtures";
|
|
|
|
vi.mock("bcryptjs", () => ({
|
|
default: {
|
|
compare: vi.fn(),
|
|
},
|
|
}));
|
|
|
|
import bcrypt from "bcryptjs";
|
|
import { POST } from "./route";
|
|
|
|
const mockCompare = vi.mocked(bcrypt.compare);
|
|
|
|
beforeEach(() => {
|
|
resetPrismaMock();
|
|
mockCompare.mockReset();
|
|
});
|
|
|
|
describe("POST /api/auth/login", () => {
|
|
it("logs in successfully with correct credentials", async () => {
|
|
prismaMock.user.findUnique.mockResolvedValue(TEST_USER as never);
|
|
mockCompare.mockResolvedValue(true as never);
|
|
|
|
const req = createRequest("/api/auth/login", {
|
|
method: "POST",
|
|
body: { username: "testuser", password: "password123" },
|
|
});
|
|
const res = await POST(req, { params: Promise.resolve({}) });
|
|
const { status, data } = await parseJsonResponse(res);
|
|
|
|
expect(status).toBe(200);
|
|
expect(data.id).toBe(TEST_USER.id);
|
|
expect(data.username).toBe("testuser");
|
|
expect(data.avatar).toBe("🐱");
|
|
});
|
|
|
|
it("returns 401 when user not found", async () => {
|
|
prismaMock.user.findUnique.mockResolvedValue(null as never);
|
|
|
|
const req = createRequest("/api/auth/login", {
|
|
method: "POST",
|
|
body: { username: "nonexistent", password: "password123" },
|
|
});
|
|
const res = await POST(req, { params: Promise.resolve({}) });
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it("returns 401 when password is wrong", async () => {
|
|
prismaMock.user.findUnique.mockResolvedValue(TEST_USER as never);
|
|
mockCompare.mockResolvedValue(false as never);
|
|
|
|
const req = createRequest("/api/auth/login", {
|
|
method: "POST",
|
|
body: { username: "testuser", password: "wrongpassword" },
|
|
});
|
|
const res = await POST(req, { params: Promise.resolve({}) });
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it("returns 400 when fields are missing", async () => {
|
|
const req = createRequest("/api/auth/login", {
|
|
method: "POST",
|
|
body: {},
|
|
});
|
|
const res = await POST(req, { params: Promise.resolve({}) });
|
|
expect(res.status).toBe(400);
|
|
});
|
|
});
|