import { expect } from "chai"; import request from "supertest"; import { createApp } from "../src/app.js"; import { prisma } from "../src/db/prisma.js"; import { resetDatabase } from "../test-support/reset-db.js"; const validSignup = { firstName: "Nicolas", lastName: "Lefevre", email: "nicolas@example.com", password: "correct-horse-battery-staple", }; describe("Auth", () => { const app = createApp(); beforeEach(async () => { await resetDatabase(); }); after(async () => { await prisma.$disconnect(); }); describe("POST /auth/signup", () => { it("creates a profile and its house, and sets a session cookie", async () => { const res = await request(app).post("/auth/signup").send(validSignup); expect(res.status).to.equal(201); expect(res.body).to.include({ firstName: "Nicolas", lastName: "Lefevre", email: "nicolas@example.com", }); expect(res.body).to.not.have.property("passwordHash"); expect(res.body.houseId).to.be.a("number"); expect(res.headers["set-cookie"]?.[0]).to.include("session="); }); it("rejects a duplicate email with 409", async () => { await request(app).post("/auth/signup").send(validSignup); const res = await request(app).post("/auth/signup").send(validSignup); expect(res.status).to.equal(409); }); it("rejects an invalid payload with 400", async () => { const res = await request(app) .post("/auth/signup") .send({ firstName: "X", lastName: "Y", email: "not-an-email", password: "short" }); expect(res.status).to.equal(400); }); }); describe("POST /auth/login", () => { beforeEach(async () => { await request(app).post("/auth/signup").send(validSignup); }); it("logs in with correct credentials", async () => { const res = await request(app) .post("/auth/login") .send({ email: validSignup.email, password: validSignup.password }); expect(res.status).to.equal(200); expect(res.body.email).to.equal(validSignup.email); }); it("rejects a wrong password with 401", async () => { const res = await request(app) .post("/auth/login") .send({ email: validSignup.email, password: "wrong-password" }); expect(res.status).to.equal(401); }); it("rejects an unknown email with 401", async () => { const res = await request(app) .post("/auth/login") .send({ email: "nobody@example.com", password: validSignup.password }); expect(res.status).to.equal(401); }); }); describe("GET /auth/me", () => { it("rejects requests without a session cookie", async () => { const res = await request(app).get("/auth/me"); expect(res.status).to.equal(401); }); it("returns the current profile when authenticated", async () => { const agent = request.agent(app); await agent.post("/auth/signup").send(validSignup); const res = await agent.get("/auth/me"); expect(res.status).to.equal(200); expect(res.body.email).to.equal(validSignup.email); }); }); });