-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathevent.test.ts
More file actions
813 lines (666 loc) · 27.8 KB
/
Copy pathevent.test.ts
File metadata and controls
813 lines (666 loc) · 27.8 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
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
import Fastify from 'fastify';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { eventRoutes } from '../routes/event';
import type { PrismaClient } from '@prisma/client';
import type { FastifyInstance,LightMyRequestResponse } from 'fastify';
// ─── Shared mock data ────────────────────────────────────────────────────────
const MOCK_USER_ID = 'user-uuid-001';
const MOCK_OTHER_USER_ID = 'user-uuid-002';
const MOCK_EVENT = {
id: 'event-uuid-001',
name: 'DevCard Conf 2025',
slug: 'devcard-conf-2025',
description: 'Annual DevCard conference',
location: 'San Francisco, CA',
organizerId: MOCK_USER_ID,
startDate: new Date('2025-09-01T09:00:00Z'),
endDate: new Date('2025-09-02T18:00:00Z'),
isPublic: true,
createdAt: new Date('2025-01-01T00:00:00Z'),
};
const MOCK_USER_PROFILE = {
id: MOCK_USER_ID,
username: 'johndoe',
displayName: 'John Doe',
bio: 'Software engineer',
pronouns: 'he/him',
company: 'Acme Corp',
avatarUrl: 'https://example.com/avatar.png',
accentColor: '#6366f1',
};
const MOCK_OTHER_USER_PROFILE = {
id: MOCK_OTHER_USER_ID,
username: 'janedoe',
displayName: 'Jane Doe',
bio: null,
pronouns: null,
company: null,
avatarUrl: null,
accentColor: '#6366f1',
};
// ─── Prisma mock ─────────────────────────────────────────────────────────────
const prismaMock = {
event: {
create: vi.fn(),
findUnique: vi.fn(),
},
eventAttendee: {
create: vi.fn(),
delete: vi.fn(),
count: vi.fn(),
},
};
// ─── App factory ─────────────────────────────────────────────────────────────
//
// Builds a minimal Fastify instance that wires up:
// • app.prisma – the Prisma mock above
// • request.jwtVerify() – overridden per-test via `mockJwtVerify`
//
// This mirrors the real app setup without touching a real DB or real JWT keys.
const mockJwtVerify = vi.fn();
async function buildApp(): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
// Decorate prisma so routes can use app.prisma.*
app.decorate('prisma', prismaMock as unknown as PrismaClient);
// Decorate jwtVerify on the request prototype so request.jwtVerify() resolves
// to whatever the current test wants.
app.decorateRequest('jwtVerify', function () {
return mockJwtVerify();
});
app.decorate('authenticate', async function (request, reply) {
try {
const payload = await request.jwtVerify();
if (payload) { request.user = payload as typeof request.user; }
} catch {
return reply.status(401).send({ error: 'Unauthorized' });
}
});
// Register with the same prefix used in production (app.ts) so that
// tests exercise routes at their real paths — /api/events, /api/events/:slug, etc.
await app.register(eventRoutes, { prefix: '/api/events' });
await app.ready();
return app;
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
/** Returns a valid JWT-authenticated inject payload */
function authHeader(): Record<string, string> {
return { Authorization: 'Bearer mock-token' };
}
/** Injects a POST /api/events request */
async function createEvent(
app: FastifyInstance,
body: Record<string, unknown>,
authenticated = true,
): Promise<LightMyRequestResponse> {
return app.inject({
method: 'POST',
url: '/api/events',
headers: authenticated ? authHeader() : {},
payload: body,
});
}
// ─── Test suite ──────────────────────────────────────────────────────────────
describe('Events API', () => {
let app: FastifyInstance;
beforeEach(async () => {
vi.clearAllMocks();
// Default: authenticated as MOCK_USER_ID
mockJwtVerify.mockResolvedValue({ id: MOCK_USER_ID });
// Default: user has no recent joins (spam heuristic inactive).
prismaMock.eventAttendee.count.mockResolvedValue(0);
app = await buildApp();
});
afterEach(async () => {
await app.close();
});
// ── POST /api/events ───────────────────────────────────────────────────────
describe('POST /api/events — create event', () => {
const validBody = {
name: 'DevCard Conf 2025',
description: 'Annual DevCard conference',
location: 'San Francisco, CA',
startDate: '2025-09-01T09:00:00Z',
endDate: '2025-09-02T18:00:00Z',
isPublic: true,
};
it('201 — creates event and returns it for authenticated organizer', async () => {
prismaMock.event.findUnique.mockResolvedValue(null); // slug is free
prismaMock.event.create.mockResolvedValue(MOCK_EVENT);
const res = await createEvent(app, validBody);
expect(res.statusCode).toBe(201);
const body = res.json();
expect(body.slug).toBe('devcard-conf-2025');
expect(body.organizerId).toBe(MOCK_USER_ID);
expect(body.location).toBe('San Francisco, CA');
// Prisma was called with correct fields
expect(prismaMock.event.create).toHaveBeenCalledOnce();
const callArg = prismaMock.event.create.mock.calls[0][0].data;
expect(callArg.name).toBe('DevCard Conf 2025');
expect(callArg.organizerId).toBe(MOCK_USER_ID);
expect(callArg.location).toBe('San Francisco, CA');
});
it('401 — rejects unauthenticated request', async () => {
mockJwtVerify.mockRejectedValue(new Error('Unauthorized'));
const res = await createEvent(app, validBody, false);
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'Unauthorized' });
});
it('400 — rejects missing required fields (no dates, no location)', async () => {
const res = await createEvent(app, { name: 'Hello World' }); // missing dates + location
expect(res.statusCode).toBe(400);
});
it('400 — rejects missing location', async () => {
const { location: _omit, ...bodyWithoutLocation } = validBody;
const res = await createEvent(app, bodyWithoutLocation);
expect(res.statusCode).toBe(400);
});
it('400 — rejects location shorter than 2 characters', async () => {
const res = await createEvent(app, { ...validBody, location: 'A' });
expect(res.statusCode).toBe(400);
});
it('400 — rejects location longer than 100 characters', async () => {
const res = await createEvent(app, { ...validBody, location: 'A'.repeat(101) });
expect(res.statusCode).toBe(400);
});
it('400 — rejects event name shorter than 3 characters', async () => {
const res = await createEvent(app, { ...validBody, name: 'Hi' });
expect(res.statusCode).toBe(400);
});
it('400 — rejects event name longer than 100 characters', async () => {
const longName = 'A'.repeat(101);
const res = await createEvent(app, { ...validBody, name: longName });
expect(res.statusCode).toBe(400);
});
it('400 — rejects invalid date format', async () => {
const res = await createEvent(app, {
...validBody,
startDate: 'not-a-date',
});
expect(res.statusCode).toBe(400);
});
it('201 — generates a unique slug when the first candidate is taken', async () => {
// First findUnique returns a conflict, second returns null (slug free)
prismaMock.event.findUnique
.mockResolvedValueOnce(MOCK_EVENT) // slug taken
.mockResolvedValueOnce(null); // randomised slug free
prismaMock.event.create.mockResolvedValue({
...MOCK_EVENT,
slug: 'devcard-conf-2025-ab12',
});
const res = await createEvent(app, validBody);
expect(res.statusCode).toBe(201);
// create was eventually called with a slug different from the base one
const createdSlug: string = prismaMock.event.create.mock.calls[0][0].data.slug;
expect(createdSlug).toMatch(/^devcard-conf-2025-[a-z0-9]+$/);
});
it('201 — isPublic defaults to true when omitted', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
prismaMock.event.create.mockResolvedValue(MOCK_EVENT);
const { isPublic: _omit, ...bodyWithoutIsPublic } = validBody;
const res = await createEvent(app, bodyWithoutIsPublic);
expect(res.statusCode).toBe(201);
const callData = prismaMock.event.create.mock.calls[0][0].data;
expect(callData.isPublic).toBe(true);
});
it('500 — returns 500 when database write fails', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
prismaMock.event.create.mockRejectedValue(new Error('DB error'));
const res = await createEvent(app, validBody);
expect(res.statusCode).toBe(500);
expect(res.json()).toMatchObject({ error: 'Failed to create event' });
});
});
// ── GET /api/events/:slug ──────────────────────────────────────────────────
describe('GET /api/events/:slug — event details', () => {
it('200 — returns event info with attendee count', async () => {
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
organizer: { username: 'johndoe', displayName: 'John Doe' },
_count: { attendees: 42 },
});
const res = await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025',
});
console.log(JSON.stringify(res.json(), null, 2));
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.slug).toBe('devcard-conf-2025');
expect(body.attendeesCount).toBe(42);
expect(body.location).toBe('San Francisco, CA');
// organizerId is exposed (public info)
expect(body.organizerId).toBe(MOCK_USER_ID);
});
it('404 — returns 404 for unknown slug', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
const res = await app.inject({
method: 'GET',
url: '/api/events/ghost-event',
});
expect(res.statusCode).toBe(404);
expect(res.json()).toMatchObject({ error: 'Event not found' });
});
it('200 — works without authentication (public endpoint)', async () => {
// Even if JWT would fail, this route should not call jwtVerify
mockJwtVerify.mockRejectedValue(new Error('Should not be called'));
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
organizer: { username: 'johndoe', displayName: 'John Doe' },
_count: { attendees: 0 },
});
const res = await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025',
// No Authorization header
});
expect(res.statusCode).toBe(200);
expect(mockJwtVerify).not.toHaveBeenCalled();
});
});
// ── POST /api/events/:slug/join ────────────────────────────────────────────
describe('POST /api/events/:slug/join — join event', () => {
it('201 — authenticated user joins an existing event (defaults to PARTICIPANT)', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
prismaMock.eventAttendee.create.mockResolvedValue({
id: 'attendee-uuid-001',
userId: MOCK_OTHER_USER_ID,
eventId: MOCK_EVENT.id,
role: 'PARTICIPANT',
flagged: false,
joinedAt: new Date(),
});
mockJwtVerify.mockResolvedValue({ id: MOCK_OTHER_USER_ID });
const res = await app.inject({
method: 'POST',
url: '/api/events/devcard-conf-2025/join',
headers: authHeader(),
});
expect(res.statusCode).toBe(201);
expect(res.json()).toMatchObject({
message: 'User joined successfully',
role: 'PARTICIPANT',
flagged: false,
});
const callData = prismaMock.eventAttendee.create.mock.calls[0][0].data;
expect(callData.eventId).toBe(MOCK_EVENT.id);
expect(callData.userId).toBe(MOCK_OTHER_USER_ID);
expect(callData.role).toBe('PARTICIPANT');
expect(callData.flagged).toBe(false);
});
it('201 — persists the chosen attendee role (ORGANIZER/MENTOR)', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
prismaMock.eventAttendee.create.mockResolvedValue({
id: 'attendee-uuid-002',
userId: MOCK_USER_ID,
eventId: MOCK_EVENT.id,
role: 'MENTOR',
flagged: false,
joinedAt: new Date(),
});
const res = await app.inject({
method: 'POST',
url: '/api/events/devcard-conf-2025/join',
headers: authHeader(),
payload: { role: 'MENTOR' },
});
expect(res.statusCode).toBe(201);
const callData = prismaMock.eventAttendee.create.mock.calls[0][0].data;
expect(callData.role).toBe('MENTOR');
});
it('400 — rejects an invalid attendee role', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
const res = await app.inject({
method: 'POST',
url: '/api/events/devcard-conf-2025/join',
headers: authHeader(),
payload: { role: 'SUPERHERO' },
});
expect(res.statusCode).toBe(400);
expect(prismaMock.eventAttendee.create).not.toHaveBeenCalled();
});
it('flags the join when the user has joined too many events recently', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
// Simulate a burst: user already joined the max in the window.
prismaMock.eventAttendee.count.mockResolvedValue(8);
prismaMock.eventAttendee.create.mockResolvedValue({
id: 'attendee-uuid-003',
userId: MOCK_USER_ID,
eventId: MOCK_EVENT.id,
role: 'PARTICIPANT',
flagged: true,
joinedAt: new Date(),
});
const res = await app.inject({
method: 'POST',
url: '/api/events/devcard-conf-2025/join',
headers: authHeader(),
});
// Join still succeeds (soft flag, no friction)...
expect(res.statusCode).toBe(201);
expect(res.json()).toMatchObject({ flagged: true });
// ...but the record is persisted as flagged for review.
const callData = prismaMock.eventAttendee.create.mock.calls[0][0].data;
expect(callData.flagged).toBe(true);
});
it('does NOT flag a normal join below the spam threshold', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
prismaMock.eventAttendee.count.mockResolvedValue(2);
prismaMock.eventAttendee.create.mockResolvedValue({
id: 'attendee-uuid-004',
userId: MOCK_USER_ID,
eventId: MOCK_EVENT.id,
role: 'PARTICIPANT',
flagged: false,
joinedAt: new Date(),
});
const res = await app.inject({
method: 'POST',
url: '/api/events/devcard-conf-2025/join',
headers: authHeader(),
});
expect(res.statusCode).toBe(201);
const callData = prismaMock.eventAttendee.create.mock.calls[0][0].data;
expect(callData.flagged).toBe(false);
});
it('401 — rejects unauthenticated request', async () => {
mockJwtVerify.mockRejectedValue(new Error('Unauthorized'));
const res = await app.inject({
method: 'POST',
url: '/api/events/devcard-conf-2025/join',
});
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'Unauthorized' });
});
it('404 — returns 404 when event does not exist', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
const res = await app.inject({
method: 'POST',
url: '/api/events/ghost-event/join',
headers: authHeader(),
});
expect(res.statusCode).toBe(404);
expect(res.json()).toMatchObject({ error: 'Event not found' });
});
it('409 — returns 409 when user already joined the event', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
// Prisma unique constraint error
const uniqueError = Object.assign(new Error('Unique constraint'), {
code: 'P2002',
});
prismaMock.eventAttendee.create.mockRejectedValue(uniqueError);
const res = await app.inject({
method: 'POST',
url: '/api/events/devcard-conf-2025/join',
headers: authHeader(),
});
expect(res.statusCode).toBe(409);
expect(res.json()).toMatchObject({ error: 'Already joined' });
});
it('500 — returns 500 on unexpected database error', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
prismaMock.eventAttendee.create.mockRejectedValue(new Error('DB error'));
const res = await app.inject({
method: 'POST',
url: '/api/events/devcard-conf-2025/join',
headers: authHeader(),
});
expect(res.statusCode).toBe(500);
expect(res.json()).toMatchObject({ error: 'Failed to join' });
});
});
// ── DELETE /api/events/:slug/leave ────────────────────────────────────────
describe('DELETE /api/events/:slug/leave — leave event', () => {
it('204 — authenticated user leaves an event they joined', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
prismaMock.eventAttendee.delete.mockResolvedValue({});
mockJwtVerify.mockResolvedValue({ id: MOCK_OTHER_USER_ID });
const res = await app.inject({
method: 'DELETE',
url: '/api/events/devcard-conf-2025/leave',
headers: authHeader(),
});
expect(res.statusCode).toBe(204);
// Verify the compound unique key used in the delete
const deleteArg = prismaMock.eventAttendee.delete.mock.calls[0][0].where;
expect(deleteArg).toMatchObject({
userId_eventId: {
userId: MOCK_OTHER_USER_ID,
eventId: MOCK_EVENT.id,
},
});
});
it('401 — rejects unauthenticated request', async () => {
mockJwtVerify.mockRejectedValue(new Error('Unauthorized'));
const res = await app.inject({
method: 'DELETE',
url: '/api/events/devcard-conf-2025/leave',
});
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'Unauthorized' });
});
it('404 — returns 404 when event does not exist', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
const res = await app.inject({
method: 'DELETE',
url: '/api/events/ghost-event/leave',
headers: authHeader(),
});
expect(res.statusCode).toBe(404);
expect(res.json()).toMatchObject({ error: 'Event not found' });
});
it('404 — returns 404 when user was never an attendee (P2025)', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
// Prisma record-not-found error
const notFoundError = Object.assign(new Error('Record not found'), {
code: 'P2025',
});
prismaMock.eventAttendee.delete.mockRejectedValue(notFoundError);
const res = await app.inject({
method: 'DELETE',
url: '/api/events/devcard-conf-2025/leave',
headers: authHeader(),
});
expect(res.statusCode).toBe(404);
expect(res.json()).toMatchObject({ error: 'User not found' });
});
it('500 — returns 500 on unexpected database error', async () => {
prismaMock.event.findUnique.mockResolvedValue(MOCK_EVENT);
prismaMock.eventAttendee.delete.mockRejectedValue(new Error('DB error'));
const res = await app.inject({
method: 'DELETE',
url: '/api/events/devcard-conf-2025/leave',
headers: authHeader(),
});
expect(res.statusCode).toBe(500);
expect(res.json()).toMatchObject({ error: 'Failed to leave' });
});
});
// ── GET /api/events/:slug/attendees ───────────────────────────────────────
describe('GET /api/events/:slug/attendees — paginated attendee list', () => {
/** Builds a raw EventAttendee row as Prisma returns it (with nested user) */
function makeAttendeeRow(
profile: typeof MOCK_USER_PROFILE | typeof MOCK_OTHER_USER_PROFILE,
role: 'PARTICIPANT' | 'ORGANIZER' | 'MENTOR' = 'PARTICIPANT',
) : {
id: string;
userId: string;
eventId: string;
role: string;
joinedAt: Date;
user: typeof MOCK_USER_PROFILE | typeof MOCK_OTHER_USER_PROFILE;
} {
return {
id: `attendee-${profile.id}`,
userId: profile.id,
eventId: MOCK_EVENT.id,
role,
joinedAt: new Date(),
user: { ...profile },
};
}
it('200 — returns paginated attendees with default page/limit', async () => {
const attendeeRows = [
makeAttendeeRow(MOCK_USER_PROFILE),
makeAttendeeRow(MOCK_OTHER_USER_PROFILE),
];
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
attendees: attendeeRows,
_count: { attendees: 2 },
});
const res = await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025/attendees',
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.attendees).toHaveLength(2);
expect(body.attendees[0]).toMatchObject({
id: MOCK_USER_ID,
username: 'johndoe',
displayName: 'John Doe',
});
expect(body.pagination).toMatchObject({
page: 1,
limit: 10,
total: 2,
});
});
it('200 — respects custom page and limit query params', async () => {
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
attendees: [makeAttendeeRow(MOCK_OTHER_USER_PROFILE)],
_count: { attendees: 1 },
});
const res = await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025/attendees?page=2&limit=5',
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.pagination.page).toBe(2);
expect(body.pagination.limit).toBe(5);
// Verify skip/take were passed correctly to Prisma
const includeArg = prismaMock.event.findUnique.mock.calls[0][0].include;
expect(includeArg.attendees.skip).toBe(5); // (page-1) * limit = 1 * 5
expect(includeArg.attendees.take).toBe(5);
});
it('200 — caps limit at 50 even if higher value is requested', async () => {
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
attendees: [],
_count: { attendees: 0 },
});
const res = await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025/attendees?limit=200',
});
expect(res.statusCode).toBe(200);
const includeArg = prismaMock.event.findUnique.mock.calls[0][0].include;
expect(includeArg.attendees.take).toBe(50);
});
it('200 — treats page < 1 as page 1', async () => {
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
attendees: [],
_count: { attendees: 0 },
});
const res = await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025/attendees?page=0',
});
expect(res.statusCode).toBe(200);
const includeArg = prismaMock.event.findUnique.mock.calls[0][0].include;
expect(includeArg.attendees.skip).toBe(0); // page forced to 1 → skip = 0
});
it('200 — returns empty attendees list for event with no attendees', async () => {
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
attendees: [],
_count: { attendees: 0 },
});
const res = await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025/attendees',
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.attendees).toHaveLength(0);
expect(body.pagination.total).toBe(0);
});
it('200 — exposes the attendee role but not sensitive fields', async () => {
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
attendees: [makeAttendeeRow(MOCK_USER_PROFILE, 'ORGANIZER')],
_count: { attendees: 1 },
});
const res = await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025/attendees',
});
const attendee = res.json().attendees[0];
// These fields MUST be present
expect(attendee).toHaveProperty('id');
expect(attendee).toHaveProperty('username');
expect(attendee).toHaveProperty('displayName');
expect(attendee).toHaveProperty('accentColor');
// The attendance role is public and drives the UI badge.
expect(attendee.role).toBe('ORGANIZER');
// These fields MUST NOT be present
expect(attendee).not.toHaveProperty('email');
expect(attendee).not.toHaveProperty('provider');
expect(attendee).not.toHaveProperty('providerId');
expect(attendee).not.toHaveProperty('flagged');
});
it('404 — returns 404 for unknown event slug', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
const res = await app.inject({
method: 'GET',
url: '/api/events/ghost-event/attendees',
});
expect(res.statusCode).toBe(404);
expect(res.json()).toMatchObject({ error: 'Event not found' });
});
it('200 — attendees are ordered by joinedAt desc (latest first)', async () => {
prismaMock.event.findUnique.mockResolvedValue({
...MOCK_EVENT,
attendees: [],
});
await app.inject({
method: 'GET',
url: '/api/events/devcard-conf-2025/attendees',
});
const includeArg = prismaMock.event.findUnique.mock.calls[0][0].include;
expect(includeArg.attendees.orderBy).toMatchObject({ joinedAt: 'desc' });
});
});
// ── Slug generation edge cases ────────────────────────────────────────────
describe('Slug generation', () => {
const baseBody = {
location: 'San Francisco, CA',
startDate: '2025-09-01T09:00:00Z',
endDate: '2025-09-02T18:00:00Z',
};
it('converts spaces and special characters to hyphens', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
prismaMock.event.create.mockResolvedValue({ ...MOCK_EVENT, slug: 'my-awesome-event' });
await createEvent(app, { ...baseBody, name: 'My Awesome Event!!!' });
const slug: string = prismaMock.event.create.mock.calls[0][0].data.slug;
expect(slug).toBe('my-awesome-event');
});
it('strips leading and trailing hyphens from slug', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
prismaMock.event.create.mockResolvedValue({ ...MOCK_EVENT, slug: 'event-name' });
await createEvent(app, { ...baseBody, name: '---Event Name---' });
const slug: string = prismaMock.event.create.mock.calls[0][0].data.slug;
expect(slug).not.toMatch(/^-|-$/);
});
it('collapses multiple consecutive hyphens into one', async () => {
prismaMock.event.findUnique.mockResolvedValue(null);
prismaMock.event.create.mockResolvedValue({ ...MOCK_EVENT, slug: 'event-name' });
await createEvent(app, { ...baseBody, name: 'Event Name' });
const slug: string = prismaMock.event.create.mock.calls[0][0].data.slug;
expect(slug).not.toMatch(/--/);
});
});
});