aboutsummaryrefslogtreecommitdiffhomepage
path: root/pkgs/server/src/routes/auth.test.ts
blob: 2d606362f54f037278f7439d049c0badd7cace91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { Hono } from "hono";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { errorHandler } from "../middleware";
import { auth } from "./auth";

vi.mock("../db", () => {
	const mockUsers: Array<{
		id: string;
		username: string;
		passwordHash: string;
		createdAt: Date;
	}> = [];

	return {
		db: {
			select: vi.fn(() => ({
				from: vi.fn(() => ({
					where: vi.fn(() => ({
						limit: vi.fn(() =>
							Promise.resolve(
								mockUsers.filter((u) => u.username === "existinguser"),
							),
						),
					})),
				})),
			})),
			insert: vi.fn(() => ({
				values: vi.fn((data: { username: string; passwordHash: string }) => ({
					returning: vi.fn(() => {
						const newUser = {
							id: "test-uuid-123",
							username: data.username,
							createdAt: new Date("2024-01-01T00:00:00Z"),
						};
						mockUsers.push({ ...newUser, passwordHash: data.passwordHash });
						return Promise.resolve([newUser]);
					}),
				})),
			})),
		},
		users: {
			id: "id",
			username: "username",
			createdAt: "created_at",
		},
	};
});

vi.mock("argon2", () => ({
	hash: vi.fn((password: string) => Promise.resolve(`hashed_${password}`)),
}));

interface RegisterResponse {
	user?: {
		id: string;
		username: string;
		createdAt: string;
	};
	error?: {
		code: string;
		message: string;
	};
}

describe("POST /register", () => {
	let app: Hono;

	beforeEach(() => {
		vi.clearAllMocks();
		app = new Hono();
		app.onError(errorHandler);
		app.route("/api/auth", auth);
	});

	it("creates a new user with valid credentials", async () => {
		const res = await app.request("/api/auth/register", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				username: "testuser",
				password: "securepassword12345",
			}),
		});

		expect(res.status).toBe(201);
		const body = (await res.json()) as RegisterResponse;
		expect(body.user).toEqual({
			id: "test-uuid-123",
			username: "testuser",
			createdAt: "2024-01-01T00:00:00.000Z",
		});
	});

	it("returns 422 for invalid username", async () => {
		const res = await app.request("/api/auth/register", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				username: "",
				password: "securepassword12345",
			}),
		});

		expect(res.status).toBe(422);
		const body = (await res.json()) as RegisterResponse;
		expect(body.error?.code).toBe("VALIDATION_ERROR");
	});

	it("returns 422 for password too short", async () => {
		const res = await app.request("/api/auth/register", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				username: "testuser",
				password: "tooshort123456",
			}),
		});

		expect(res.status).toBe(422);
		const body = (await res.json()) as RegisterResponse;
		expect(body.error?.code).toBe("VALIDATION_ERROR");
	});

	it("returns 409 for existing username", async () => {
		const { db } = await import("../db");
		// eslint-disable-next-line @typescript-eslint/no-explicit-any
		vi.mocked(db.select).mockReturnValueOnce({
			from: vi.fn().mockReturnValue({
				where: vi.fn().mockReturnValue({
					limit: vi.fn().mockResolvedValue([{ id: "existing-id" }]),
				}),
			}),
		} as unknown as ReturnType<typeof db.select>);

		const res = await app.request("/api/auth/register", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				username: "existinguser",
				password: "securepassword12345",
			}),
		});

		expect(res.status).toBe(409);
		const body = (await res.json()) as RegisterResponse;
		expect(body.error?.code).toBe("USERNAME_EXISTS");
	});
});