84 lines
2.7 KiB
TypeScript
84 lines
2.7 KiB
TypeScript
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import request from "supertest";
|
|
import type { FastifyInstance } from "fastify";
|
|
import { PrismaClient } from "@prisma/client";
|
|
import { buildApp } from "../src/server";
|
|
|
|
const prisma = new PrismaClient();
|
|
let app: FastifyInstance;
|
|
|
|
beforeAll(async () => {
|
|
app = await buildApp({ AUTH_DISABLED: false, SEED_DEFAULT_BUDGET: true });
|
|
await app.ready();
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await app.close();
|
|
await prisma.$disconnect();
|
|
});
|
|
|
|
describe("Auth routes", () => {
|
|
it("rejects protected routes without a session", async () => {
|
|
const res = await request(app.server).get("/dashboard");
|
|
expect(res.status).toBe(401);
|
|
expect(res.body.code).toBe("UNAUTHENTICATED");
|
|
});
|
|
|
|
it("registers a user and grants access via cookie session", async () => {
|
|
const agent = request.agent(app.server);
|
|
const email = `reg-${Date.now()}@test.dev`;
|
|
const password = "SupersAFE123!";
|
|
|
|
const register = await agent.post("/auth/register").send({ email, password });
|
|
expect(register.status).toBe(200);
|
|
|
|
const dash = await agent.get("/dashboard");
|
|
expect(dash.status).toBe(200);
|
|
|
|
const created = await prisma.user.findUniqueOrThrow({ where: { email } });
|
|
const [catCount, planCount] = await Promise.all([
|
|
prisma.variableCategory.count({ where: { userId: created.id } }),
|
|
prisma.fixedPlan.count({ where: { userId: created.id } }),
|
|
]);
|
|
expect(catCount).toBeGreaterThan(0);
|
|
expect(planCount).toBeGreaterThan(0);
|
|
|
|
await prisma.user.deleteMany({ where: { email } });
|
|
});
|
|
|
|
it("logs in existing user and accesses dashboard", async () => {
|
|
const agent = request.agent(app.server);
|
|
const email = `login-${Date.now()}@test.dev`;
|
|
const password = "SupersAFE123!";
|
|
|
|
await agent.post("/auth/register").send({ email, password });
|
|
await agent.post("/auth/logout");
|
|
|
|
const login = await agent.post("/auth/login").send({ email, password });
|
|
expect(login.status).toBe(200);
|
|
|
|
const dash = await agent.get("/dashboard");
|
|
expect(dash.status).toBe(200);
|
|
|
|
await prisma.user.deleteMany({ where: { email } });
|
|
});
|
|
|
|
it("reports session info and handles logout", async () => {
|
|
const agent = request.agent(app.server);
|
|
const email = `session-${Date.now()}@test.dev`;
|
|
const password = "SupersAFE123!";
|
|
|
|
await agent.post("/auth/register").send({ email, password });
|
|
|
|
const session = await agent.get("/auth/session");
|
|
expect(session.status).toBe(200);
|
|
expect(session.body.userId).toBeDefined();
|
|
|
|
await agent.post("/auth/logout");
|
|
const afterLogout = await agent.get("/dashboard");
|
|
expect(afterLogout.status).toBe(401);
|
|
|
|
await prisma.user.deleteMany({ where: { email } });
|
|
});
|
|
});
|