-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.test.ts
More file actions
844 lines (730 loc) · 24.4 KB
/
Copy pathserver.test.ts
File metadata and controls
844 lines (730 loc) · 24.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
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
import Fastify, {
FastifyError,
FastifyInstance,
FastifyReply,
FastifyRequest,
} from 'fastify';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import migrateDatabase from '@/migrator/index';
import cachePlugin from '@/plugin/cache';
import communicatePlugin from '@/plugin/communicate';
import otpPlugin from '@/plugin/otp';
import rateLimitPlugin from '@/plugin/rate-limit';
import {startServer} from '@/server';
import {registerEmailChangeRoute} from '@/routes/auth/change-email';
import {registerChangePasswordRoute} from '@/routes/auth/change-password';
import {registerDeleteMeRoute} from '@/routes/auth/delete-me';
import {registerEditMeRoute} from '@/routes/auth/edit-me';
import {registerForgotPasswordRoute} from '@/routes/auth/forgot-password';
import {registerLoginRoute} from '@/routes/auth/login';
import {registerMeRoute} from '@/routes/auth/me';
import {
registerForgotPasswordOtpVerifyRoute,
registerLoginOtpVerifyRoute,
registerRegistrationOtpVerifyRoute,
} from '@/routes/auth/otp-verify';
import {registerRegistrationRoute} from '@/routes/auth/registration';
import {
registerForgotPasswordResendOtpRoute,
registerLoginResendOtpRoute,
registerRegistrationResendOtpRoute,
} from '@/routes/auth/resend-otp';
import {registerRoutes} from '@/routes/index';
import {Mode} from '@/interfaces';
import {AppConfig} from '@/interfaces/config';
vi.mock('fastify', () => {
let appConfig: AppConfig | undefined;
const storedHooks: Record<string, unknown[]> = {};
const mockApp = {
register: vi.fn(async (plugin: unknown) => {
if (typeof plugin === 'function') {
try {
await plugin(mockApp, {});
} catch {
// plugins may fail in mock context — ignore
}
}
}),
addHook: vi.fn((name: string, fn: unknown) => {
if (!storedHooks[name]) storedHooks[name] = [];
storedHooks[name].push(fn);
}),
getHook: (name: string) => storedHooks[name],
setErrorHandler: vi.fn(),
listen: vi.fn(),
close: vi.fn(),
post: vi.fn(),
get: vi.fn(),
patch: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
log: {
error: vi.fn(),
info: vi.fn(),
},
buildResponse: vi.fn((statusCode, message, data, meta) => ({
statusCode,
message,
meta,
})),
set appConfig(val: AppConfig) {
appConfig = val;
},
get appConfig(): AppConfig | undefined {
return appConfig;
},
};
return {
default: vi.fn(() => mockApp),
};
});
vi.mock('@/validators/config', () => ({
validateConfig: vi.fn(c => c),
}));
vi.mock('@/migrator/index', () => ({
default: vi.fn(),
}));
vi.mock('@/routes/index', () => ({
registerRoutes: vi.fn(),
}));
vi.mock('@/routes/auth/registration', () => ({
registerRegistrationRoute: vi.fn(),
}));
vi.mock('@/routes/auth/login', () => ({
registerLoginRoute: vi.fn(),
}));
vi.mock('@/routes/auth/change-password', () => ({
registerChangePasswordRoute: vi.fn(),
}));
vi.mock('@/routes/auth/forgot-password', () => ({
registerForgotPasswordRoute: vi.fn(),
}));
vi.mock('@/routes/auth/otp-verify', () => ({
registerForgotPasswordOtpVerifyRoute: vi.fn(),
registerLoginOtpVerifyRoute: vi.fn(),
registerRegistrationOtpVerifyRoute: vi.fn(),
}));
vi.mock('@/routes/auth/resend-otp', () => ({
registerForgotPasswordResendOtpRoute: vi.fn(),
registerLoginResendOtpRoute: vi.fn(),
registerRegistrationResendOtpRoute: vi.fn(),
}));
vi.mock('@/routes/auth/me', () => ({
registerMeRoute: vi.fn(),
}));
vi.mock('@/routes/auth/delete-me', () => ({
registerDeleteMeRoute: vi.fn(),
}));
vi.mock('@/routes/auth/edit-me', () => ({
registerEditMeRoute: vi.fn(),
}));
vi.mock('@/routes/auth/change-email', () => ({
registerEmailChangeRoute: vi.fn(),
}));
vi.mock('@/lib/server/welcome', () => ({
showWelcomeScreen: vi.fn(),
}));
const mockConfig: AppConfig = {
application: {
name: 'Test App',
logLevel: 'info',
},
infrastructure: {
database: {
engine: 'sqlite',
connection: {url: ':memory:'},
},
},
docs: {
openapi: {
enabled: true,
path: '/docs',
info: {title: 'Test', description: 'Test API', version: '1.0'},
},
},
data: {
models: {
users: {
fields: {
id: {type: 'integer', primaryKey: true},
},
},
},
},
};
type MockedApp = FastifyInstance & {
register: ReturnType<typeof vi.fn>;
addHook: ReturnType<typeof vi.fn>;
getHook: (name: string) => unknown[] | undefined;
setErrorHandler: ReturnType<typeof vi.fn>;
listen: ReturnType<typeof vi.fn>;
close: ReturnType<typeof vi.fn>;
post: ReturnType<typeof vi.fn>;
get: ReturnType<typeof vi.fn>;
patch: ReturnType<typeof vi.fn>;
put: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
log: {
error: ReturnType<typeof vi.fn>;
info: ReturnType<typeof vi.fn>;
};
buildResponse: ReturnType<typeof vi.fn>;
};
describe('Server', () => {
let mockApp: MockedApp;
beforeEach(() => {
vi.clearAllMocks();
mockApp = Fastify() as unknown as MockedApp;
});
afterEach(() => {
vi.restoreAllMocks();
});
const runStart = async (
mode: Mode = 'dev',
verbose: boolean = false,
migrate: boolean = false,
) => {
await startServer(mockConfig, 3000, mode, verbose, migrate);
};
it('should initialize fastify with correct logger based on configuration', async () => {
const fastifyMock = vi.mocked(Fastify);
await startServer(mockConfig, 3000, 'dev');
expect(fastifyMock).toHaveBeenCalledWith(
expect.objectContaining({
logger: expect.objectContaining({
level: mockConfig.application.logLevel,
}),
}),
);
fastifyMock.mockClear();
await startServer(mockConfig, 3000, 'prod');
expect(fastifyMock).toHaveBeenCalledWith(
expect.objectContaining({
logger: expect.objectContaining({
level: mockConfig.application.logLevel,
}),
}),
);
});
it('should respect custom logLevel from application config in prod mode', async () => {
const fastifyMock = vi.mocked(Fastify);
const customConfig: AppConfig = {
...mockConfig,
application: {name: 'Test App', logLevel: 'warn'},
};
await startServer(customConfig, 3000, 'prod');
expect(fastifyMock).toHaveBeenCalledWith(
expect.objectContaining({
logger: expect.objectContaining({level: 'warn'}),
}),
);
fastifyMock.mockClear();
await startServer(customConfig, 3000, 'dev');
expect(fastifyMock).toHaveBeenCalledWith(
expect.objectContaining({
logger: expect.objectContaining({level: 'warn'}),
}),
);
});
it('should override logger level to debug when verbose is true', async () => {
const fastifyMock = vi.mocked(Fastify);
// Test verbose in prod mode
await startServer(mockConfig, 3000, 'prod', true);
expect(fastifyMock).toHaveBeenCalledWith(
expect.objectContaining({
logger: expect.objectContaining({level: 'debug'}),
}),
);
fastifyMock.mockClear();
// Test verbose in dev mode (should still be debug)
await startServer(mockConfig, 3000, 'dev', true);
expect(fastifyMock).toHaveBeenCalledWith(
expect.objectContaining({
logger: expect.objectContaining({level: 'debug'}),
}),
);
});
it('should register routes hook correctly', async () => {
const {routes} = await startServer(mockConfig, 3000, 'dev');
const addHookMock = mockApp.addHook;
expect(addHookMock).toHaveBeenCalledWith('onRoute', expect.any(Function));
const hookCallback = addHookMock.mock.calls[0][1] as (opts: {
method: string | string[];
url: string;
}) => void;
hookCallback({method: 'GET', url: '/test'});
hookCallback({method: ['POST', 'PUT'], url: '/multi'});
expect(routes).toEqual(
expect.arrayContaining([
{method: 'GET', url: '/test'},
{method: 'POST/PUT', url: '/multi'},
]),
);
});
it('should register plugins and routes', async () => {
await runStart('dev', false, true);
expect(mockApp.register).toHaveBeenCalledTimes(9);
const prefixCall = mockApp.register.mock.calls.find(
([, opts]) => opts?.prefix === '/api',
);
expect(prefixCall).toBeDefined();
expect(migrateDatabase).toHaveBeenCalledWith(mockConfig);
expect(registerRoutes).toHaveBeenCalled();
});
it('should skip migration when migrate is false', async () => {
await runStart('dev', false, false);
expect(migrateDatabase).not.toHaveBeenCalled();
});
it('should not register swagger if disabled', async () => {
const disabledSwaggerConfig = {
...mockConfig,
docs: {
openapi: {...mockConfig.docs.openapi, enabled: false},
},
} as unknown as AppConfig;
await startServer(disabledSwaggerConfig, 3000, 'prod');
expect(mockApp.register).toHaveBeenCalledTimes(6);
});
it('should not register routes if models are missing/empty', async () => {
const noModelsConfig = {
...mockConfig,
data: {models: {}},
} as unknown as AppConfig;
await startServer(noModelsConfig, 3000, 'prod');
expect(registerRoutes).toHaveBeenCalledWith(
expect.any(Object),
noModelsConfig,
);
expect(mockApp.register).toHaveBeenCalledWith(
expect.any(Function),
expect.objectContaining({prefix: '/api'}),
);
});
describe('Error Handler', () => {
type TestError = FastifyError & {
code?: string;
validation?: FastifyError['validation'];
};
type ErrorHandler = (
err: TestError,
req: FastifyRequest,
reply: FastifyReply,
) => void;
let errorHandler: ErrorHandler;
let mockReq: FastifyRequest;
let mockReply: FastifyReply;
beforeEach(async () => {
await runStart();
errorHandler = mockApp.setErrorHandler.mock.calls[0][0] as ErrorHandler;
mockReq = {
log: {error: vi.fn()},
} as unknown as FastifyRequest;
mockReply = {
status: vi.fn().mockReturnThis(),
send: vi.fn(),
} as unknown as FastifyReply;
});
const createError = (
msg: string,
code?: string,
statusCode?: number,
validation?: FastifyError['validation'],
): TestError => {
const e = new Error(msg) as TestError;
if (code) e.code = code;
if (statusCode) e.statusCode = statusCode;
if (validation) e.validation = validation;
return e;
};
it('should handle standard fastify error code fallback', () => {
const err = createError('generic error');
errorHandler(err, mockReq, mockReply);
expect(mockReply.status).toHaveBeenCalledWith(500);
expect(mockReply.send).toHaveBeenCalledWith(
expect.objectContaining({statusCode: 500, message: 'generic error'}),
);
});
it('should process Data exceptions (22xxx) as 400', () => {
const err = createError('Invalid input syntax', '22P02');
errorHandler(err, mockReq, mockReply);
expect(mockReply.status).toHaveBeenCalledWith(400);
expect(mockReply.send).toHaveBeenCalledWith(
expect.objectContaining({statusCode: 400}),
);
});
it('should process Integrity violations (23xxx) as 400', () => {
const err = createError('Unique constraint violation', '23505');
errorHandler(err, mockReq, mockReply);
expect(mockReply.status).toHaveBeenCalledWith(400);
});
it('should process Connection exceptions (08xxx) as 503', () => {
const err = createError('Connection failed', '08001');
errorHandler(err, mockReq, mockReply);
expect(mockReply.status).toHaveBeenCalledWith(503);
});
it('should route unknown database errors appropriately (e.g. 42P01 undefined table)', () => {
const err = createError('Undefined table', '42P01');
errorHandler(err, mockReq, mockReply);
expect(mockReply.status).toHaveBeenCalledWith(500);
});
it('should respect incoming status code if specified, provided it is valid HTTP', () => {
const err = createError('Custom 422 object', '99999', 422);
errorHandler(err, mockReq, mockReply);
expect(mockReply.status).toHaveBeenCalledWith(422);
});
it('should send err.body directly when present', () => {
const err = createError('Business error', undefined, 422);
(err as unknown as Record<string, unknown>).body = {
code: 422,
message: 'Business error',
data: null,
};
errorHandler(err, mockReq, mockReply);
expect(mockReply.status).toHaveBeenCalledWith(422);
expect(mockReply.send).toHaveBeenCalledWith({
code: 422,
message: 'Business error',
data: null,
});
});
it('should pass validation errors in metadata payload', () => {
// Create a mock validation error block conforming to fastify's validation structure
const validationPayload = [
{message: 'field required'},
] as unknown as FastifyError['validation'];
const err = createError(
'Validation failed',
undefined,
400,
validationPayload,
);
errorHandler(err, mockReq, mockReply);
expect(mockReply.send).toHaveBeenCalledWith(
expect.objectContaining({
meta: expect.objectContaining({
validation: [{message: 'field required'}],
}),
}),
);
});
it('should default to 500 if an invalid status code is provided with an error code (hits line 148)', () => {
const err = createError('Bad error', 'SOME_CODE', 200);
errorHandler(err, mockReq, mockReply);
expect(mockReply.status).toHaveBeenCalledWith(500);
});
});
it('should return the app instance and routes', async () => {
const {app, routes} = await startServer(mockConfig, 3000, 'dev');
expect(app).toBe(mockApp);
expect(Array.isArray(routes)).toBe(true);
});
it('should call enforceSSP in the global preValidation hook', async () => {
const {app} = await startServer(mockConfig, 3000, 'dev');
const mockApp = app as MockedApp;
const preValidationHooks = mockApp.getHook('preValidation');
expect(preValidationHooks).toBeDefined();
expect(preValidationHooks!.length).toBeGreaterThan(0);
const mockRequest = {
routeOptions: {config: {apiIdentifier: 'test'}},
query: {},
body: {},
params: {},
};
const enforceSSP = vi.fn();
(mockApp as unknown as Record<string, unknown>).enforceSSP = enforceSSP;
for (const hook of preValidationHooks!) {
await (hook as (...args: unknown[]) => unknown)(mockRequest);
}
expect(enforceSSP).toHaveBeenCalledWith(mockRequest);
});
describe('Redis and Rate Limit Configuration', () => {
it('should register rate-limit plugin when rateLimit is configured', async () => {
const configWithRateLimit: AppConfig = {
...mockConfig,
application: {
name: 'Test App',
logLevel: 'info',
rateLimit: {
enabled: true,
max: 100,
timeWindow: '15m',
},
},
};
const registerMock = mockApp.register;
await startServer(configWithRateLimit, 3000, 'dev');
const rateLimitRegistration = registerMock.mock.calls.find(
(call: unknown[]) => call[0] === rateLimitPlugin,
);
expect(rateLimitRegistration).toBeDefined();
});
it('should not register rate-limit plugin when rateLimit is not configured', async () => {
const registerMock = mockApp.register;
await startServer(mockConfig, 3000, 'dev');
const rateLimitRegistration = registerMock.mock.calls.find(
(call: unknown[]) => call[0] === rateLimitPlugin,
);
expect(rateLimitRegistration).toBeUndefined();
});
it('should disable rate-limit when enabled is false', async () => {
const configWithDisabledRateLimit: AppConfig = {
...mockConfig,
application: {
name: 'Test App',
logLevel: 'info',
rateLimit: {
enabled: false,
max: 100,
timeWindow: '15m',
},
},
};
const registerMock = mockApp.register;
await startServer(configWithDisabledRateLimit, 3000, 'dev');
const rateLimitRegistration = registerMock.mock.calls.find(
(call: unknown[]) => call[0] === rateLimitPlugin,
);
expect(rateLimitRegistration).toBeUndefined();
});
});
describe('Authentication Configuration', () => {
it('should register auth plugin when auth is configured', async () => {
const configWithAuth: AppConfig = {
...mockConfig,
authentication: {
enabled: true,
provider: {
type: 'up-auth',
config: {
userModel: {
model: 'users',
idField: 'id',
usernameField: 'email',
passwordField: 'password',
},
},
},
},
};
const registerMock = mockApp.register;
await startServer(configWithAuth, 3000, 'dev');
// Our startServer calls register(authPlugin) if config.auth is present
expect(registerMock).toHaveBeenCalledWith(
expect.any(Function), // authPlugin
);
});
it('should register otp plugin when auth is up-auth with mfaRequired', async () => {
const configWithMfa: AppConfig = {
...mockConfig,
infrastructure: {
...mockConfig.infrastructure,
cache: {
engine: 'redis',
connection: {url: 'redis://localhost:6379'},
},
},
integrations: {
email: {
provider: 'dummy',
},
},
authentication: {
enabled: true,
provider: {
type: 'up-auth',
config: {
userModel: {
model: 'users',
idField: 'id',
usernameField: 'email',
passwordField: 'password',
},
jwtSecret: 'this-is-a-long-enough-secret-key-for-testing',
mfaRequired: true,
},
},
},
};
const registerMock = mockApp.register;
await startServer(configWithMfa, 3000, 'dev');
expect(registerMock).toHaveBeenCalledWith(otpPlugin);
});
it('should register auth routes conditionally based on config', async () => {
const configWithAll: AppConfig = {
...mockConfig,
integrations: {
email: {
provider: 'dummy',
},
},
authentication: {
enabled: true,
provider: {
type: 'up-auth',
config: {
userModel: {
model: 'users',
idField: 'id',
usernameField: 'email',
passwordField: 'password',
isVerifiedField: 'is_active',
},
jwtSecret: 'test-secret',
mfaRequired: true,
},
},
},
};
await startServer(configWithAll, 3000, 'dev');
expect(registerRegistrationRoute).toHaveBeenCalled();
expect(registerLoginRoute).toHaveBeenCalled();
expect(registerChangePasswordRoute).toHaveBeenCalled();
expect(registerForgotPasswordRoute).toHaveBeenCalled();
expect(registerLoginOtpVerifyRoute).toHaveBeenCalled();
expect(registerRegistrationOtpVerifyRoute).toHaveBeenCalled();
expect(registerForgotPasswordOtpVerifyRoute).toHaveBeenCalled();
expect(registerLoginResendOtpRoute).toHaveBeenCalled();
expect(registerRegistrationResendOtpRoute).toHaveBeenCalled();
expect(registerForgotPasswordResendOtpRoute).toHaveBeenCalled();
expect(registerMeRoute).toHaveBeenCalled();
expect(registerDeleteMeRoute).toHaveBeenCalled();
expect(registerEditMeRoute).toHaveBeenCalled();
expect(registerEmailChangeRoute).toHaveBeenCalled();
});
it('should not register registration OTP verify route when isVerifiedField is not set', async () => {
const configWithoutVerified: AppConfig = {
...mockConfig,
integrations: {
email: {
provider: 'dummy',
},
},
authentication: {
enabled: true,
provider: {
type: 'up-auth',
config: {
userModel: {
model: 'users',
idField: 'id',
usernameField: 'email',
passwordField: 'password',
},
jwtSecret: 'test-secret',
mfaRequired: true,
},
},
},
};
await startServer(configWithoutVerified, 3000, 'dev');
expect(registerRegistrationOtpVerifyRoute).not.toHaveBeenCalled();
expect(registerRegistrationResendOtpRoute).not.toHaveBeenCalled();
expect(registerEmailChangeRoute).not.toHaveBeenCalled();
});
it('should not register login OTP verify route when mfa is not required', async () => {
const configWithoutMfa: AppConfig = {
...mockConfig,
integrations: {
email: {
provider: 'dummy',
},
},
authentication: {
enabled: true,
provider: {
type: 'up-auth',
config: {
userModel: {
model: 'users',
idField: 'id',
usernameField: 'email',
passwordField: 'password',
},
jwtSecret: 'test-secret',
},
},
},
};
await startServer(configWithoutMfa, 3000, 'dev');
expect(registerLoginOtpVerifyRoute).not.toHaveBeenCalled();
expect(registerLoginResendOtpRoute).not.toHaveBeenCalled();
});
it('should not register forgot-password routes when email is not configured', async () => {
const configWithoutEmail: AppConfig = {
...mockConfig,
authentication: {
enabled: true,
provider: {
type: 'up-auth',
config: {
userModel: {
model: 'users',
idField: 'id',
usernameField: 'email',
passwordField: 'password',
},
jwtSecret: 'test-secret',
mfaRequired: true,
},
},
},
};
await startServer(configWithoutEmail, 3000, 'dev');
expect(registerForgotPasswordRoute).not.toHaveBeenCalled();
expect(registerForgotPasswordOtpVerifyRoute).not.toHaveBeenCalled();
expect(registerForgotPasswordResendOtpRoute).not.toHaveBeenCalled();
});
});
describe('Integrations Configuration', () => {
it('should register communicate plugin when integrations.email is configured', async () => {
const configWithIntegrations: AppConfig = {
...mockConfig,
integrations: {
email: {
provider: 'dummy',
},
},
};
const registerMock = mockApp.register;
await startServer(configWithIntegrations, 3000, 'dev');
expect(registerMock).toHaveBeenCalledWith(communicatePlugin);
});
it('should not register communicate plugin when integrations.email is not configured', async () => {
const registerMock = mockApp.register;
await startServer(mockConfig, 3000, 'dev');
// Assert that none of the registered calls are the communicatePlugin
const communicatePluginCall = registerMock.mock.calls.find(
(call: unknown[]) => call[0] === communicatePlugin,
);
expect(communicatePluginCall).toBeUndefined();
});
});
describe('Cache Configuration', () => {
it('should register cache plugin when cache is configured', async () => {
const configWithCache: AppConfig = {
...mockConfig,
infrastructure: {
...mockConfig.infrastructure,
cache: {
engine: 'redis',
connection: {url: 'redis://localhost:6379'},
},
},
};
const registerMock = mockApp.register;
await startServer(configWithCache, 3000, 'dev');
const cachePluginCall = registerMock.mock.calls.find(
(call: unknown[]) => call[0] === cachePlugin,
);
expect(cachePluginCall).toBeDefined();
});
it('should register cache plugin even when cache is not configured', async () => {
const registerMock = mockApp.register;
await startServer(mockConfig, 3000, 'dev');
const cachePluginCall = registerMock.mock.calls.find(
(call: unknown[]) => call[0] === cachePlugin,
);
expect(cachePluginCall).toBeDefined();
});
});
});