/ opencodehub / tests / integration / auth-register-route.test.ts
Swadhin Biswas Feature/ai code reviewer (#73) · 8/2/2026
105a287
210 lines · 5.4 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/**
 * Integration tests for POST /api/auth/register
 */
import { beforeEach, describe, expect, it, vi } from "vitest";

/* ─── hoisted mocks ─── */
const mocks = vi.hoisted(() => ({
  applyRateLimitMock: vi.fn().mockResolvedValue(null),
  hashPasswordMock: vi.fn().mockResolvedValue("hashed_pw_123"),
  createSessionMock: vi.fn().mockResolvedValue({
    id: "sess_1",
    userId: "usr_new",
    token: "sesstoken",
    userAgent: "vitest",
    ipAddress: null,
    expiresAt: new Date(Date.now() + 86400000).toISOString(),
    createdAt: new Date().toISOString(),
  }),
  createTokenMock: vi.fn().mockResolvedValue("jwt_register_token"),
  generateIdMock: vi.fn().mockReturnValue("usr_new"),
  isValidUsernameMock: vi.fn().mockReturnValue(true),
  isValidEmailMock: vi.fn().mockReturnValue(true),
  insertMock: vi
    .fn()
    .mockReturnValue({ values: vi.fn().mockResolvedValue([]) }),
  fakeSchema: { users: "users", sessions: "sessions" },
}));

/* ─── module mocks ─── */
vi.mock("@/db", () => ({
  getDatabase: () => mockDb,
  schema: mocks.fakeSchema,
}));

vi.mock("@/db/schema", () => ({
  users: "users",
  sessions: "sessions",
}));

vi.mock("@/middleware/rate-limit", () => ({
  applyRateLimit: mocks.applyRateLimitMock,
}));

vi.mock("@/lib/auth", () => ({
  hashPassword: mocks.hashPasswordMock,
  createSession: mocks.createSessionMock,
  createToken: mocks.createTokenMock,
  validatePasswordStrength: vi.fn().mockReturnValue({ valid: true, errors: [] }),
}));

vi.mock("@/lib/utils", () => ({
  generateId: mocks.generateIdMock,
  isValidUsername: mocks.isValidUsernameMock,
  isValidEmail: mocks.isValidEmailMock,
  now: () => new Date(),
}));

vi.mock("@/lib/validation", () => ({
  RegisterUserSchema: {
    safeParse: vi.fn().mockReturnValue({ success: true }),
  },
}));

vi.mock("@/lib/logger", () => ({
  logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
}));

vi.mock("@/lib/errors", () => ({
  withErrorHandler: (fn: any) => fn,
}));

vi.mock("drizzle-orm", () => ({
  eq: vi.fn((...a: any[]) => a),
}));

/* ─── helpers ─── */
function makeDb() {
  return {
    query: {
      users: {
        findFirst: vi.fn().mockResolvedValue(null), // no existing user
      },
    },
    insert: mocks.insertMock,
  };
}

let mockDb: ReturnType<typeof makeDb>;
const readJson = (r: Response) => r.json();

function makeRequest(body: Record<string, unknown>) {
  return {
    request: new Request("http://localhost/api/auth/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    }),
    cookies: { set: vi.fn(), delete: vi.fn() },
  } as any;
}

/* ─── import route ─── */
import { POST } from "@/pages/api/auth/register";

/* ─── tests ─── */
describe("POST /api/auth/register", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockDb = makeDb();
    delete process.env.ENABLE_REGISTRATION;
  });

  it("returns 201 with token for valid registration", async () => {
    const res = await POST(
      makeRequest({
        username: "newuser",
        email: "[email protected]",
        password: "password123",
        displayName: "New User",
      }),
    );
    expect(res.status).toBe(201);
    const json = await readJson(res);
    expect(json.data.user.username).toBe("newuser");
    expect(json.data.token).toBe("jwt_register_token");
  });

  it("returns 400 when registration is disabled", async () => {
    process.env.ENABLE_REGISTRATION = "false";
    const res = await POST(
      makeRequest({
        username: "newuser",
        email: "[email protected]",
        password: "password123",
      }),
    );
    expect(res.status).toBe(400);
  });

  it("returns 409 when username already taken", async () => {
    mockDb.query.users.findFirst.mockResolvedValue({
      id: "usr_1",
      username: "newuser",
      email: "[email protected]",
    });
    const res = await POST(
      makeRequest({
        username: "newuser",
        email: "[email protected]",
        password: "password123",
      }),
    );
    expect(res.status).toBe(409);
  });

  it("returns 409 when email already registered", async () => {
    mockDb.query.users.findFirst.mockResolvedValue({
      id: "usr_1",
      username: "other",
      email: "[email protected]",
    });
    const res = await POST(
      makeRequest({
        username: "newuser",
        email: "[email protected]",
        password: "password123",
      }),
    );
    expect(res.status).toBe(409);
  });

  it("returns 400 when username format invalid", async () => {
    mocks.isValidUsernameMock.mockReturnValue(false);
    const res = await POST(
      makeRequest({
        username: "bad user!",
        email: "[email protected]",
        password: "password123",
      }),
    );
    expect(res.status).toBe(400);
  });

  it("returns 400 when email format invalid", async () => {
    mocks.isValidEmailMock.mockReturnValue(false);
    const res = await POST(
      makeRequest({
        username: "newuser",
        email: "not-an-email",
        password: "password123",
      }),
    );
    expect(res.status).toBe(400);
  });

  it("returns rate limit response when rate limited", async () => {
    mocks.applyRateLimitMock.mockResolvedValue(
      new Response(JSON.stringify({ error: "Rate limited" }), { status: 429 }),
    );
    const res = await POST(
      makeRequest({
        username: "newuser",
        email: "[email protected]",
        password: "password123",
      }),
    );
    expect(res.status).toBe(429);
  });
});