eyrun-api/tests/login.test.ts
2026-02-08 13:39:33 +01:00

70 lines
1.7 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest";
import type { FastifyInstance } from "fastify";
import { createTestApp, cleanDb, signupUser } from "./helpers.js";
let app: FastifyInstance;
beforeAll(async () => {
app = await createTestApp();
});
afterAll(async () => {
await app.close();
});
beforeEach(async () => {
await cleanDb();
});
describe("POST /login", () => {
it("sends OTP for an existing user", async () => {
await signupUser(app, "test@example.com", "Org");
const res = await app.inject({
method: "POST",
url: "/login",
payload: { email: "test@example.com" },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ message: "OTP sent to your email" });
});
it("returns 404 if user does not exist", async () => {
const res = await app.inject({
method: "POST",
url: "/login",
payload: { email: "unknown@example.com" },
});
expect(res.statusCode).toBe(404);
expect(res.json().error).toMatch(/sign up/i);
});
it("returns 400 if email is missing", async () => {
const res = await app.inject({
method: "POST",
url: "/login",
payload: {},
});
expect(res.statusCode).toBe(400);
});
it("rate limits after 3 requests", async () => {
await signupUser(app, "ratelimit@example.com", "Org");
for (let i = 0; i < 3; i++) {
await app.inject({ method: "POST", url: "/login", payload: { email: "ratelimit@example.com" } });
}
const res = await app.inject({
method: "POST",
url: "/login",
payload: { email: "ratelimit@example.com" },
});
expect(res.statusCode).toBe(429);
});
});