/ opencodehub / tests / integration / auth-me-route.test.ts
Swadhin Biswas feat: production readiness — fix critical bugs, achieve 100% test pass rate, complete documentation · 4/30/2026
ac8f8cc
188 lines · 4.7 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
/**
 * Integration tests for GET / PATCH / DELETE /api/auth/me
 */
import { beforeEach, describe, expect, it, vi } from "vitest";

/* ─── hoisted mocks ─── */
const mocks = vi.hoisted(() => ({
  getUserFromRequestMock: vi.fn().mockResolvedValue({
    userId: "usr_1",
    username: "alice",
    email: "[email protected]",
  }),
  updateMock: vi.fn().mockReturnValue({
    set: vi.fn().mockReturnValue({
      where: vi.fn().mockResolvedValue([]),
    }),
  }),
  deleteMock: vi.fn().mockReturnValue({
    where: vi.fn().mockResolvedValue([]),
  }),
  logAuditMock: vi.fn().mockResolvedValue(undefined),
  getRequestMetaMock: vi
    .fn()
    .mockReturnValue({ ip: "127.0.0.1", userAgent: "vitest" }),
  fakeSchema: { users: "users" },
}));

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

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

vi.mock("@/lib/auth", () => ({
  getUserFromRequest: mocks.getUserFromRequestMock,
}));

vi.mock("@/lib/audit", () => ({
  logAudit: mocks.logAuditMock,
  getRequestMeta: mocks.getRequestMetaMock,
}));

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 ─── */
const fakeUser = {
  id: "usr_1",
  username: "alice",
  email: "[email protected]",
  displayName: "Alice",
  bio: "Developer",
  avatarUrl: null,
  location: "NYC",
  website: "",
  company: "ACME",
  isAdmin: false,
  emailVerified: true,
  twoFactorEnabled: false,
  createdAt: new Date(),
};

function makeDb() {
  return {
    query: {
      users: {
        findFirst: vi.fn().mockResolvedValue(fakeUser),
      },
    },
    update: mocks.updateMock,
    delete: mocks.deleteMock,
  };
}

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

function ctx(method: string, body?: Record<string, unknown>) {
  const init: RequestInit = {
    method,
    headers: { "Content-Type": "application/json" },
  };
  if (body) init.body = JSON.stringify(body);
  return {
    request: new Request("http://localhost/api/auth/me", init),
    cookies: { set: vi.fn(), delete: vi.fn() },
  } as any;
}

/* ─── import routes ─── */
import { DELETE, GET, PATCH } from "@/pages/api/auth/me";

/* ─── tests ─── */
describe("GET /api/auth/me", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockDb = makeDb();
    mocks.getUserFromRequestMock.mockResolvedValue({
      userId: "usr_1",
      username: "alice",
      email: "[email protected]",
    });
  });

  it("returns 200 with user profile", async () => {
    const res = await GET(ctx("GET"));
    expect(res.status).toBe(200);
    const json = await readJson(res);
    expect(json.data.username).toBe("alice");
    expect(json.data.email).toBe("[email protected]");
  });

  it("returns 401 when not authenticated", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await GET(ctx("GET"));
    expect(res.status).toBe(401);
  });

  it("returns 404 when user no longer exists", async () => {
    mockDb.query.users.findFirst.mockResolvedValue(null);
    const res = await GET(ctx("GET"));
    expect(res.status).toBe(404);
  });
});

describe("PATCH /api/auth/me", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockDb = makeDb();
    mocks.getUserFromRequestMock.mockResolvedValue({
      userId: "usr_1",
      username: "alice",
      email: "[email protected]",
    });
  });

  it("returns 200 when profile updated", async () => {
    const res = await PATCH(ctx("PATCH", { displayName: "Alice W" }));
    expect(res.status).toBe(200);
    const json = await readJson(res);
    expect(json.data.message).toContain("updated");
  });

  it("returns 401 when not authenticated", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await PATCH(ctx("PATCH", { displayName: "x" }));
    expect(res.status).toBe(401);
  });
});

describe("DELETE /api/auth/me", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockDb = makeDb();
    mocks.getUserFromRequestMock.mockResolvedValue({
      userId: "usr_1",
      username: "alice",
      email: "[email protected]",
    });
  });

  it("returns 200 and deletes account", async () => {
    const res = await DELETE(ctx("DELETE"));
    expect(res.status).toBe(200);
    const json = await readJson(res);
    expect(json.data.message).toContain("deleted");
  });

  it("returns 401 when not authenticated", async () => {
    mocks.getUserFromRequestMock.mockResolvedValue(null);
    const res = await DELETE(ctx("DELETE"));
    expect(res.status).toBe(401);
  });
});