File size: 9,428 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/**
 * Tests for GET /api/settings and PATCH /api/settings
 *
 * GET:
 *   - 404 when no user found
 *   - returns name, dailyGoalXp, lichessUsername, chesscomUsername
 *   - null username fields coerced to empty string
 *
 * PATCH:
 *   - 400 for invalid JSON body
 *   - 400 for empty updates (no valid fields)
 *   - name: valid update, empty string rejected, >50 chars rejected, trimmed
 *   - dailyGoalXp: valid values accepted, invalid value rejected
 *   - lichessUsername: updates and clears (empty string → null)
 *   - chesscomUsername: updates and clears (empty string → null)
 *   - combined update of multiple fields
 *   - response shape matches GET response shape
 *   - DB errors propagate as 500
 */

import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";

// ---------------------------------------------------------------------------
// Mock prisma
// ---------------------------------------------------------------------------

const mockUserFindFirst = vi.fn();
const mockUserUpdate = vi.fn();

vi.mock("@/lib/db", () => ({
  prisma: {
    user: {
      findFirst: (...args: unknown[]) => mockUserFindFirst(...args),
      update: (...args: unknown[]) => mockUserUpdate(...args),
    },
  },
}));

import { GET, PATCH } from "../route";

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

const baseUser = {
  id: 1,
  name: "Player One",
  dailyGoalXp: 100,
  lichessUsername: "magnus",
  chesscomUsername: "hikaru",
};

function makeGet(): NextRequest {
  return new NextRequest("http://localhost/api/settings");
}

function makePatch(body?: Record<string, unknown>): NextRequest {
  return new NextRequest("http://localhost/api/settings", {
    method: "PATCH",
    body: body !== undefined ? JSON.stringify(body) : undefined,
    headers: { "Content-Type": "application/json" },
  });
}

async function json(res: Response): Promise<unknown> {
  return res.json();
}

// ---------------------------------------------------------------------------
// Tests — GET
// ---------------------------------------------------------------------------

describe("GET /api/settings", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns 404 when no user found", async () => {
    mockUserFindFirst.mockResolvedValue(null);
    const res = await GET(makeGet());
    expect(res.status).toBe(404);
  });

  it("returns settings fields", async () => {
    mockUserFindFirst.mockResolvedValue(baseUser);
    const res = await GET(makeGet());
    expect(res.status).toBe(200);

    const body = await json(res) as Record<string, unknown>;
    expect(body.name).toBe("Player One");
    expect(body.dailyGoalXp).toBe(100);
    expect(body.lichessUsername).toBe("magnus");
    expect(body.chesscomUsername).toBe("hikaru");
  });

  it("coerces null lichessUsername to empty string", async () => {
    mockUserFindFirst.mockResolvedValue({ ...baseUser, lichessUsername: null });
    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    expect(body.lichessUsername).toBe("");
  });

  it("coerces null chesscomUsername to empty string", async () => {
    mockUserFindFirst.mockResolvedValue({ ...baseUser, chesscomUsername: null });
    const res = await GET(makeGet());
    const body = await json(res) as Record<string, unknown>;
    expect(body.chesscomUsername).toBe("");
  });

  it("propagates DB errors as 500", async () => {
    mockUserFindFirst.mockRejectedValue(new Error("DB error"));
    const res = await GET(makeGet());
    expect(res.status).toBe(500);
  });
});

// ---------------------------------------------------------------------------
// Tests — PATCH
// ---------------------------------------------------------------------------

describe("PATCH /api/settings", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockUserUpdate.mockResolvedValue(baseUser);
  });

  it("returns 400 for invalid JSON body", async () => {
    const req = new NextRequest("http://localhost/api/settings", {
      method: "PATCH",
      body: "not-json{{{",
      headers: { "Content-Type": "application/json" },
    });
    const res = await PATCH(req);
    expect(res.status).toBe(400);
  });

  it("returns 400 when no valid fields provided", async () => {
    const res = await PATCH(makePatch({ unknown_field: "x" }));
    expect(res.status).toBe(400);
    const body = await json(res) as Record<string, unknown>;
    expect(body.error).toMatch(/no valid fields/i);
  });

  it("updates name successfully", async () => {
    mockUserUpdate.mockResolvedValue({ ...baseUser, name: "New Name" });
    const res = await PATCH(makePatch({ name: "New Name" }));
    expect(res.status).toBe(200);

    expect(mockUserUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ name: "New Name" }),
      }),
    );
  });

  it("trims name whitespace", async () => {
    mockUserUpdate.mockResolvedValue({ ...baseUser, name: "Trimmed" });
    await PATCH(makePatch({ name: "  Trimmed  " }));
    expect(mockUserUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ name: "Trimmed" }),
      }),
    );
  });

  it("rejects empty name", async () => {
    const res = await PATCH(makePatch({ name: "" }));
    expect(res.status).toBe(400);
    const body = await json(res) as Record<string, unknown>;
    expect(body.error).toMatch(/name must be/i);
  });

  it("rejects name longer than 50 characters", async () => {
    const res = await PATCH(makePatch({ name: "a".repeat(51) }));
    expect(res.status).toBe(400);
    const body = await json(res) as Record<string, unknown>;
    expect(body.error).toMatch(/name must be/i);
  });

  it("accepts a name of exactly 50 characters", async () => {
    mockUserUpdate.mockResolvedValue({ ...baseUser, name: "a".repeat(50) });
    const res = await PATCH(makePatch({ name: "a".repeat(50) }));
    expect(res.status).toBe(200);
  });

  it("updates dailyGoalXp with valid value", async () => {
    for (const valid of [50, 100, 150, 200, 300]) {
      mockUserUpdate.mockResolvedValue({ ...baseUser, dailyGoalXp: valid });
      const res = await PATCH(makePatch({ dailyGoalXp: valid }));
      expect(res.status).toBe(200);
    }
  });

  it("rejects invalid dailyGoalXp value", async () => {
    const res = await PATCH(makePatch({ dailyGoalXp: 75 }));
    expect(res.status).toBe(400);
    const body = await json(res) as Record<string, unknown>;
    expect(body.error).toMatch(/dailyGoalXp/i);
  });

  it("updates lichessUsername", async () => {
    mockUserUpdate.mockResolvedValue({ ...baseUser, lichessUsername: "leelaAI" });
    const res = await PATCH(makePatch({ lichessUsername: "leelaAI" }));
    expect(res.status).toBe(200);
    expect(mockUserUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ lichessUsername: "leelaAI" }),
      }),
    );
  });

  it("clears lichessUsername when empty string provided", async () => {
    mockUserUpdate.mockResolvedValue({ ...baseUser, lichessUsername: null });
    await PATCH(makePatch({ lichessUsername: "" }));
    expect(mockUserUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ lichessUsername: null }),
      }),
    );
  });

  it("updates chesscomUsername", async () => {
    mockUserUpdate.mockResolvedValue({ ...baseUser, chesscomUsername: "nakamura" });
    const res = await PATCH(makePatch({ chesscomUsername: "nakamura" }));
    expect(res.status).toBe(200);
  });

  it("clears chesscomUsername when empty string provided", async () => {
    mockUserUpdate.mockResolvedValue({ ...baseUser, chesscomUsername: null });
    await PATCH(makePatch({ chesscomUsername: "" }));
    expect(mockUserUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ chesscomUsername: null }),
      }),
    );
  });

  it("allows combined update of multiple fields", async () => {
    mockUserUpdate.mockResolvedValue({ ...baseUser, name: "Updated", dailyGoalXp: 150 });
    const res = await PATCH(makePatch({ name: "Updated", dailyGoalXp: 150 }));
    expect(res.status).toBe(200);
    expect(mockUserUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ name: "Updated", dailyGoalXp: 150 }),
      }),
    );
  });

  it("response shape matches GET response shape", async () => {
    const updatedUser = { ...baseUser, name: "New", lichessUsername: null, chesscomUsername: null };
    mockUserUpdate.mockResolvedValue(updatedUser);
    const res = await PATCH(makePatch({ name: "New" }));
    const body = await json(res) as Record<string, unknown>;

    expect(body).toHaveProperty("name");
    expect(body).toHaveProperty("dailyGoalXp");
    expect(body).toHaveProperty("lichessUsername");
    expect(body).toHaveProperty("chesscomUsername");
    // null coercion
    expect(body.lichessUsername).toBe("");
    expect(body.chesscomUsername).toBe("");
  });

  it("propagates DB errors as 500", async () => {
    mockUserUpdate.mockRejectedValue(new Error("DB constraint failed"));
    const res = await PATCH(makePatch({ name: "ValidName" }));
    expect(res.status).toBe(500);
  });
});