@omnitron-dev/testing 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/async/deferred.d.ts +15 -0
  2. package/dist/async/deferred.js +35 -0
  3. package/dist/async/deferred.js.map +1 -0
  4. package/dist/async/events.d.ts +32 -0
  5. package/dist/async/events.js +176 -0
  6. package/dist/async/events.js.map +1 -0
  7. package/dist/async/index.d.ts +5 -0
  8. package/dist/async/index.js +6 -0
  9. package/dist/async/index.js.map +1 -0
  10. package/dist/async/mock-timer.d.ts +19 -0
  11. package/dist/async/mock-timer.js +87 -0
  12. package/dist/async/mock-timer.js.map +1 -0
  13. package/dist/async/retry.d.ts +8 -0
  14. package/dist/async/retry.js +36 -0
  15. package/dist/async/retry.js.map +1 -0
  16. package/dist/async/wait.d.ts +10 -0
  17. package/dist/async/wait.js +35 -0
  18. package/dist/async/wait.js.map +1 -0
  19. package/dist/docker/database-manager.d.ts +22 -0
  20. package/dist/docker/database-manager.js +97 -0
  21. package/dist/docker/database-manager.js.map +1 -0
  22. package/dist/docker/docker-test-manager.d.ts +44 -0
  23. package/dist/docker/docker-test-manager.js +805 -0
  24. package/dist/docker/docker-test-manager.js.map +1 -0
  25. package/dist/docker/index.d.ts +4 -0
  26. package/dist/docker/index.js +4 -0
  27. package/dist/docker/index.js.map +1 -0
  28. package/dist/docker/redis-manager.d.ts +12 -0
  29. package/dist/docker/redis-manager.js +453 -0
  30. package/dist/docker/redis-manager.js.map +1 -0
  31. package/dist/docker/types.d.ts +103 -0
  32. package/dist/docker/types.js +2 -0
  33. package/dist/docker/types.js.map +1 -0
  34. package/dist/errors.d.ts +15 -0
  35. package/dist/errors.js +28 -0
  36. package/dist/errors.js.map +1 -0
  37. package/dist/helpers/assertions.d.ts +6 -0
  38. package/dist/helpers/assertions.js +37 -0
  39. package/dist/helpers/assertions.js.map +1 -0
  40. package/dist/helpers/console.d.ts +1 -0
  41. package/dist/helpers/console.js +23 -0
  42. package/dist/helpers/console.js.map +1 -0
  43. package/dist/helpers/index.d.ts +3 -0
  44. package/dist/helpers/index.js +4 -0
  45. package/dist/helpers/index.js.map +1 -0
  46. package/dist/helpers/temp-dir.d.ts +2 -0
  47. package/dist/helpers/temp-dir.js +13 -0
  48. package/dist/helpers/temp-dir.js.map +1 -0
  49. package/dist/index.d.ts +2 -0
  50. package/dist/index.js +2 -0
  51. package/dist/index.js.map +1 -1
  52. package/dist/performance/index.d.ts +2 -0
  53. package/dist/performance/index.js +3 -0
  54. package/dist/performance/index.js.map +1 -0
  55. package/dist/performance/memory-detector.d.ts +9 -0
  56. package/dist/performance/memory-detector.js +61 -0
  57. package/dist/performance/memory-detector.js.map +1 -0
  58. package/dist/performance/perf-timer.d.ts +9 -0
  59. package/dist/performance/perf-timer.js +49 -0
  60. package/dist/performance/perf-timer.js.map +1 -0
  61. package/package.json +28 -2
  62. package/src/async/README.md +336 -0
  63. package/src/async/deferred.ts +98 -0
  64. package/src/async/events.ts +386 -0
  65. package/src/async/index.ts +48 -0
  66. package/src/async/mock-timer.ts +220 -0
  67. package/src/async/retry.ts +118 -0
  68. package/src/async/wait.ts +151 -0
  69. package/src/docker/database-manager.ts +242 -0
  70. package/src/docker/docker-test-manager.ts +1186 -0
  71. package/src/docker/index.ts +48 -0
  72. package/src/docker/redis-manager.ts +738 -0
  73. package/src/docker/types.ts +216 -0
  74. package/src/errors.ts +31 -0
  75. package/src/helpers/assertions.ts +171 -0
  76. package/src/helpers/console.ts +74 -0
  77. package/src/helpers/index.ts +15 -0
  78. package/src/helpers/temp-dir.ts +50 -0
  79. package/src/index.ts +2 -0
  80. package/src/performance/index.ts +11 -0
  81. package/src/performance/memory-detector.ts +166 -0
  82. package/src/performance/perf-timer.ts +146 -0
  83. package/src/titan/container-utils.ts +128 -0
  84. package/src/titan/index.ts +59 -0
  85. package/src/titan/redis-test-utils.ts +566 -0
  86. package/src/titan/test-application.ts +154 -0
  87. package/src/titan/test-fixtures.ts +304 -0
  88. package/src/titan/test-mocks.ts +336 -0
  89. package/src/titan/test-module.ts +231 -0
@@ -0,0 +1,566 @@
1
+ /**
2
+ * Redis Test Utilities
3
+ *
4
+ * Enterprise-grade testing utilities for Redis-based components
5
+ * Provides comprehensive fixtures and helpers for testing Redis functionality
6
+ */
7
+
8
+ import { Redis, RedisOptions } from 'ioredis';
9
+ import { RedisManager } from '@omnitron-dev/titan/module/redis';
10
+ import { RedisService } from '@omnitron-dev/titan/module/redis';
11
+ import { EventEmitter } from '@omnitron-dev/eventemitter';
12
+ import { Errors } from '@omnitron-dev/titan/errors';
13
+ import type { ILogger } from '@omnitron-dev/titan/module/logger';
14
+
15
+ /**
16
+ * Create a null logger for testing
17
+ */
18
+ function createTestNullLogger(): ILogger {
19
+ const noop = () => {};
20
+ return {
21
+ trace: noop,
22
+ debug: noop,
23
+ info: noop,
24
+ warn: noop,
25
+ error: noop,
26
+ fatal: noop,
27
+ child: () => createTestNullLogger(),
28
+ time: () => noop,
29
+ isLevelEnabled: () => false,
30
+ _pino: null as any,
31
+ };
32
+ }
33
+
34
+ /**
35
+ * Redis test fixture configuration
36
+ */
37
+ export interface RedisTestFixtureOptions {
38
+ withManager?: boolean;
39
+ withService?: boolean;
40
+ db?: number;
41
+ host?: string;
42
+ port?: number;
43
+ namespace?: string;
44
+ password?: string;
45
+ lazyConnect?: boolean;
46
+ enableReadyCheck?: boolean;
47
+ maxRetriesPerRequest?: number;
48
+ retryStrategy?: () => null;
49
+ }
50
+
51
+ /**
52
+ * Redis test fixture containing all necessary components
53
+ */
54
+ export interface RedisTestFixture {
55
+ client: Redis;
56
+ manager?: RedisManager;
57
+ service?: RedisService;
58
+ cleanup: () => Promise<void>;
59
+ options: RedisOptions;
60
+ }
61
+
62
+ /**
63
+ * Create a Redis test fixture with proper cleanup
64
+ */
65
+ export async function createRedisTestFixture(options: RedisTestFixtureOptions = {}): Promise<RedisTestFixture> {
66
+ const {
67
+ withManager = false,
68
+ withService = false,
69
+ db = 15, // Use test database
70
+ host = 'localhost',
71
+ port = 6379,
72
+ namespace = 'test',
73
+ lazyConnect = false,
74
+ enableReadyCheck = true,
75
+ maxRetriesPerRequest = 1,
76
+ retryStrategy = () => null, // Disable retries in tests
77
+ } = options;
78
+
79
+ const redisOptions: RedisOptions = {
80
+ host,
81
+ port,
82
+ db,
83
+ password: options.password,
84
+ lazyConnect,
85
+ enableReadyCheck,
86
+ maxRetriesPerRequest,
87
+ retryStrategy,
88
+ };
89
+
90
+ // Create primary client
91
+ const client = new Redis(redisOptions);
92
+
93
+ // Wait for connection if not lazy
94
+ if (!lazyConnect) {
95
+ await new Promise<void>((resolve, reject) => {
96
+ const timeout = setTimeout(() => {
97
+ client.removeAllListeners();
98
+ reject(Errors.timeout('Redis connection in test fixture', 10000));
99
+ }, 10000); // 10 second timeout
100
+
101
+ client.once('ready', () => {
102
+ clearTimeout(timeout);
103
+ resolve();
104
+ });
105
+ client.once('error', (error) => {
106
+ clearTimeout(timeout);
107
+ reject(error);
108
+ });
109
+
110
+ // Ensure connection starts
111
+ if (client.status === 'wait') {
112
+ client.connect().catch(reject);
113
+ }
114
+ });
115
+ }
116
+
117
+ let manager: RedisManager | undefined;
118
+ let service: RedisService | undefined;
119
+
120
+ // Create manager if requested
121
+ if (withManager) {
122
+ // Use type assertion to avoid ioredis version compatibility issues
123
+ const clientConfigs = [
124
+ {
125
+ namespace: 'default',
126
+ ...redisOptions,
127
+ db: redisOptions.db, // Use the test DB
128
+ },
129
+ {
130
+ namespace,
131
+ ...redisOptions,
132
+ db: redisOptions.db, // Use the test DB
133
+ },
134
+ ...(namespace !== 'cache'
135
+ ? [
136
+ {
137
+ namespace: 'cache',
138
+ ...redisOptions,
139
+ db: 14, // Use different DB for cache namespace
140
+ },
141
+ ]
142
+ : []),
143
+ ] as any;
144
+
145
+ manager = new RedisManager({ clients: clientConfigs }, createTestNullLogger());
146
+ await manager.onModuleInit();
147
+ }
148
+
149
+ // Create service if requested
150
+ if (withService && manager) {
151
+ service = new RedisService(manager);
152
+ }
153
+
154
+ // Cleanup function
155
+ const cleanup = async () => {
156
+ try {
157
+ // Clear all data in test database
158
+ await client.flushdb();
159
+
160
+ // Cleanup manager
161
+ if (manager) {
162
+ await manager.onModuleDestroy();
163
+ }
164
+
165
+ // Close client
166
+ client.disconnect();
167
+
168
+ // Remove all listeners
169
+ client.removeAllListeners();
170
+ } catch (error) {
171
+ console.error('Cleanup error:', error);
172
+ }
173
+ };
174
+
175
+ return {
176
+ client,
177
+ manager,
178
+ service,
179
+ cleanup,
180
+ options: redisOptions,
181
+ };
182
+ }
183
+
184
+ /**
185
+ * Cleanup Redis test fixture
186
+ */
187
+ export async function cleanupRedisTestFixture(fixture: RedisTestFixture): Promise<void> {
188
+ if (fixture && fixture.cleanup) {
189
+ await fixture.cleanup();
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Wait for Redis operation to complete
195
+ */
196
+ export async function waitForRedis(operation: () => Promise<any>, timeout = 5000): Promise<any> {
197
+ return Promise.race([
198
+ operation(),
199
+ new Promise((_, reject) => setTimeout(() => reject(Errors.timeout('Redis operation', timeout)), timeout)),
200
+ ]);
201
+ }
202
+
203
+ /**
204
+ * Create mock Redis client for unit tests
205
+ */
206
+ export function createMockRedis(): any {
207
+ const data = new Map<string, any>();
208
+ const pubsub = new EventEmitter();
209
+ const locks = new Map<string, { token: string; ttl: number }>();
210
+
211
+ const mock = {
212
+ // Connection
213
+ connect: jest.fn().mockResolvedValue(undefined),
214
+ disconnect: jest.fn().mockImplementation(() => {
215
+ mock.emit('close');
216
+ }),
217
+ quit: jest.fn().mockResolvedValue('OK'),
218
+ ping: jest.fn().mockResolvedValue('PONG'),
219
+
220
+ // Basic operations
221
+ get: jest.fn().mockImplementation(async (key: string) => data.get(key) ?? null),
222
+
223
+ set: jest.fn().mockImplementation(async (key: string, value: any, ...args: any[]) => {
224
+ data.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
225
+
226
+ // Handle TTL
227
+ if (args[0] === 'EX' && args[1]) {
228
+ setTimeout(() => data.delete(key), args[1] * 1000);
229
+ } else if (args[0] === 'PX' && args[1]) {
230
+ setTimeout(() => data.delete(key), args[1]);
231
+ }
232
+
233
+ return 'OK';
234
+ }),
235
+
236
+ setex: jest.fn().mockImplementation(async (key: string, ttl: number, value: any) => {
237
+ data.set(key, String(value));
238
+ setTimeout(() => data.delete(key), ttl * 1000);
239
+ return 'OK';
240
+ }),
241
+
242
+ del: jest.fn().mockImplementation(async (...keys: string[]) => {
243
+ let count = 0;
244
+ for (const key of keys) {
245
+ if (data.delete(key)) count++;
246
+ }
247
+ return count;
248
+ }),
249
+
250
+ exists: jest.fn().mockImplementation(async (...keys: string[]) => keys.filter((k) => data.has(k)).length),
251
+
252
+ expire: jest.fn().mockImplementation(async (key: string, ttl: number) => {
253
+ if (data.has(key)) {
254
+ setTimeout(() => data.delete(key), ttl * 1000);
255
+ return 1;
256
+ }
257
+ return 0;
258
+ }),
259
+
260
+ ttl: jest.fn().mockImplementation(async (key: string) => (data.has(key) ? -1 : -2)),
261
+
262
+ keys: jest.fn().mockImplementation(async (pattern: string) => {
263
+ if (pattern === '*') return Array.from(data.keys());
264
+ const regex = new RegExp(pattern.replace('*', '.*'));
265
+ return Array.from(data.keys()).filter((k) => regex.test(k));
266
+ }),
267
+
268
+ // Hash operations
269
+ hget: jest.fn().mockImplementation(async (key: string, field: string) => {
270
+ const hash = data.get(key);
271
+ if (!hash || typeof hash !== 'object') return null;
272
+ return hash[field] ?? null;
273
+ }),
274
+
275
+ hset: jest.fn().mockImplementation(async (key: string, field: string, value: any) => {
276
+ let hash = data.get(key);
277
+ if (!hash || typeof hash !== 'object') {
278
+ hash = {};
279
+ data.set(key, hash);
280
+ }
281
+ const isNew = !(field in hash);
282
+ hash[field] = value;
283
+ return isNew ? 1 : 0;
284
+ }),
285
+
286
+ hgetall: jest.fn().mockImplementation(async (key: string) => {
287
+ const hash = data.get(key);
288
+ return hash && typeof hash === 'object' ? hash : {};
289
+ }),
290
+
291
+ // List operations
292
+ lpush: jest.fn().mockImplementation(async (key: string, ...values: any[]) => {
293
+ let list = data.get(key);
294
+ if (!Array.isArray(list)) {
295
+ list = [];
296
+ data.set(key, list);
297
+ }
298
+ list.unshift(...values);
299
+ return list.length;
300
+ }),
301
+
302
+ rpush: jest.fn().mockImplementation(async (key: string, ...values: any[]) => {
303
+ let list = data.get(key);
304
+ if (!Array.isArray(list)) {
305
+ list = [];
306
+ data.set(key, list);
307
+ }
308
+ list.push(...values);
309
+ return list.length;
310
+ }),
311
+
312
+ lpop: jest.fn().mockImplementation(async (key: string) => {
313
+ const list = data.get(key);
314
+ if (!Array.isArray(list) || list.length === 0) return null;
315
+ return list.shift();
316
+ }),
317
+
318
+ rpop: jest.fn().mockImplementation(async (key: string) => {
319
+ const list = data.get(key);
320
+ if (!Array.isArray(list) || list.length === 0) return null;
321
+ return list.pop();
322
+ }),
323
+
324
+ lrange: jest.fn().mockImplementation(async (key: string, start: number, stop: number) => {
325
+ const list = data.get(key);
326
+ if (!Array.isArray(list)) return [];
327
+ return list.slice(start, stop + 1);
328
+ }),
329
+
330
+ // Set operations
331
+ sadd: jest.fn().mockImplementation(async (key: string, ...members: any[]) => {
332
+ let set = data.get(key);
333
+ if (!set || !(set instanceof Set)) {
334
+ set = new Set();
335
+ data.set(key, set);
336
+ }
337
+ let added = 0;
338
+ for (const member of members) {
339
+ if (!set.has(member)) {
340
+ set.add(member);
341
+ added++;
342
+ }
343
+ }
344
+ return added;
345
+ }),
346
+
347
+ smembers: jest.fn().mockImplementation(async (key: string) => {
348
+ const set = data.get(key);
349
+ if (!set || !(set instanceof Set)) return [];
350
+ return Array.from(set);
351
+ }),
352
+
353
+ sismember: jest.fn().mockImplementation(async (key: string, member: any) => {
354
+ const set = data.get(key);
355
+ if (!set || !(set instanceof Set)) return 0;
356
+ return set.has(member) ? 1 : 0;
357
+ }),
358
+
359
+ // Pub/Sub
360
+ subscribe: jest.fn().mockImplementation(async (...channels: string[]) => {
361
+ for (const channel of channels) {
362
+ pubsub.on(channel, () => {});
363
+ }
364
+ return channels.length;
365
+ }),
366
+
367
+ unsubscribe: jest.fn().mockImplementation(async (...channels: string[]) => {
368
+ for (const channel of channels) {
369
+ pubsub.removeAllListeners(channel);
370
+ }
371
+ return channels.length;
372
+ }),
373
+
374
+ publish: jest.fn().mockImplementation(async (channel: string, message: string) => {
375
+ const listeners = pubsub.listenerCount(channel);
376
+ pubsub.emit(channel, message);
377
+ return listeners;
378
+ }),
379
+
380
+ // Transactions
381
+ multi: jest.fn().mockImplementation(() => {
382
+ const commands: any[] = [];
383
+ const multi = {
384
+ get: (key: string) => {
385
+ commands.push(['get', key]);
386
+ return multi;
387
+ },
388
+ set: (key: string, value: any) => {
389
+ commands.push(['set', key, value]);
390
+ return multi;
391
+ },
392
+ del: (...keys: string[]) => {
393
+ commands.push(['del', ...keys]);
394
+ return multi;
395
+ },
396
+ exec: jest.fn().mockImplementation(async () => {
397
+ const results = [];
398
+ for (const [cmd, ...args] of commands) {
399
+ try {
400
+ const result = await (mock as any)[cmd](...args);
401
+ results.push([null, result]);
402
+ } catch (error) {
403
+ results.push([error, null]);
404
+ }
405
+ }
406
+ return results;
407
+ }),
408
+ };
409
+ return multi;
410
+ }),
411
+
412
+ // Lock operations (for RedisLock decorator)
413
+ eval: jest.fn().mockImplementation(async (script: string, ...args: any[]) => {
414
+ // Simple lock implementation
415
+ const [numKeys, ...params] = args;
416
+ const keys = params.slice(0, numKeys);
417
+ const values = params.slice(numKeys);
418
+
419
+ if (script.includes('redis.call("set"')) {
420
+ // Lock acquisition script
421
+ const [key] = keys;
422
+ const [token, ttl] = values;
423
+
424
+ if (locks.has(key)) {
425
+ return 0; // Lock already held
426
+ }
427
+
428
+ locks.set(key, { token, ttl: parseInt(ttl) });
429
+ setTimeout(() => {
430
+ const lock = locks.get(key);
431
+ if (lock && lock.token === token) {
432
+ locks.delete(key);
433
+ }
434
+ }, parseInt(ttl));
435
+
436
+ return 1; // Lock acquired
437
+ } else if (script.includes('redis.call("del"')) {
438
+ // Lock release script
439
+ const [key] = keys;
440
+ const [token] = values;
441
+
442
+ const lock = locks.get(key);
443
+ if (lock && lock.token === token) {
444
+ locks.delete(key);
445
+ return 1; // Lock released
446
+ }
447
+
448
+ return 0; // Lock not held or wrong token
449
+ }
450
+
451
+ return null;
452
+ }),
453
+
454
+ // Utility
455
+ flushdb: jest.fn().mockImplementation(async () => {
456
+ data.clear();
457
+ locks.clear();
458
+ return 'OK';
459
+ }),
460
+
461
+ flushall: jest.fn().mockImplementation(async () => {
462
+ data.clear();
463
+ locks.clear();
464
+ return 'OK';
465
+ }),
466
+
467
+ // Event emitter methods
468
+ on: jest.fn().mockImplementation((event: string, handler: (...args: any[]) => any) => {
469
+ pubsub.on(event, handler);
470
+ return mock;
471
+ }),
472
+
473
+ once: jest.fn().mockImplementation((event: string, handler: (...args: any[]) => any) => {
474
+ pubsub.once(event, handler);
475
+ return mock;
476
+ }),
477
+
478
+ off: jest.fn().mockImplementation((event: string, handler: (...args: any[]) => any) => {
479
+ pubsub.off(event, handler);
480
+ return mock;
481
+ }),
482
+
483
+ emit: jest.fn().mockImplementation((event: string, ...args: any[]) => {
484
+ pubsub.emit(event, ...args);
485
+ return true;
486
+ }),
487
+
488
+ removeAllListeners: jest.fn().mockImplementation((event?: string) => {
489
+ if (event) {
490
+ pubsub.removeAllListeners(event);
491
+ } else {
492
+ pubsub.removeAllListeners();
493
+ }
494
+ return mock;
495
+ }),
496
+
497
+ // Duplicate for creating subscriber clients
498
+ duplicate: jest.fn().mockImplementation(() => createMockRedis()),
499
+
500
+ // Status
501
+ status: 'ready',
502
+
503
+ // Internal access for testing
504
+ __data: data,
505
+ __locks: locks,
506
+ __pubsub: pubsub,
507
+ };
508
+
509
+ // Emit ready event on next tick
510
+ process.nextTick(() => {
511
+ mock.emit('ready');
512
+ });
513
+
514
+ return mock;
515
+ }
516
+
517
+ /**
518
+ * Redis performance testing utilities
519
+ */
520
+ export class RedisPerformanceTester {
521
+ private metrics: Map<string, { count: number; totalTime: number }> = new Map();
522
+
523
+ async measure<T>(operation: string, fn: () => Promise<T>): Promise<T> {
524
+ const start = process.hrtime.bigint();
525
+ try {
526
+ const result = await fn();
527
+ const end = process.hrtime.bigint();
528
+ const duration = Number(end - start) / 1_000_000; // Convert to ms
529
+
530
+ const metric = this.metrics.get(operation) || { count: 0, totalTime: 0 };
531
+ metric.count++;
532
+ metric.totalTime += duration;
533
+ this.metrics.set(operation, metric);
534
+
535
+ return result;
536
+ } catch (error) {
537
+ const end = process.hrtime.bigint();
538
+ const duration = Number(end - start) / 1_000_000;
539
+
540
+ const metric = this.metrics.get(operation) || { count: 0, totalTime: 0 };
541
+ metric.count++;
542
+ metric.totalTime += duration;
543
+ this.metrics.set(operation, metric);
544
+
545
+ throw error;
546
+ }
547
+ }
548
+
549
+ getMetrics() {
550
+ const results: Record<string, any> = {};
551
+
552
+ for (const [operation, metric] of this.metrics) {
553
+ results[operation] = {
554
+ count: metric.count,
555
+ totalTime: metric.totalTime,
556
+ avgTime: metric.totalTime / metric.count,
557
+ };
558
+ }
559
+
560
+ return results;
561
+ }
562
+
563
+ reset() {
564
+ this.metrics.clear();
565
+ }
566
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Test Application Utilities
3
+ *
4
+ * Provides utilities for creating and managing test applications
5
+ * in Titan framework tests.
6
+ */
7
+
8
+ import { Application } from '@omnitron-dev/titan';
9
+ import { Container } from '@omnitron-dev/titan/nexus';
10
+ import type { IApplicationOptions } from '@omnitron-dev/titan';
11
+ import { Errors } from '@omnitron-dev/titan/errors';
12
+
13
+ /**
14
+ * Test application builder with simplified API
15
+ */
16
+ export class TestApplication {
17
+ private app: Application | null = null;
18
+ private container: Container;
19
+ private cleanupFns: (() => Promise<void> | void)[] = [];
20
+
21
+ constructor(private options: Partial<IApplicationOptions> = {}) {
22
+ this.container = new Container();
23
+ }
24
+
25
+ /**
26
+ * Create test application with modules
27
+ */
28
+ static async create(rootModule: any, options: Partial<IApplicationOptions> = {}): Promise<TestApplication> {
29
+ const testApp = new TestApplication(options);
30
+ await testApp.bootstrap(rootModule);
31
+ return testApp;
32
+ }
33
+
34
+ /**
35
+ * Bootstrap the application
36
+ */
37
+ async bootstrap(rootModule: any): Promise<void> {
38
+ // Create application with test defaults
39
+ this.app = await Application.create({
40
+ ...this.options,
41
+ modules: [rootModule],
42
+ logger: (this.options as any)['logger'] ?? false, // Disable logging by default in tests
43
+ gracefulShutdown: false,
44
+ disableCoreModules: !(this.options as any)['registerCoreModules'],
45
+ });
46
+
47
+ // Store container reference - use public getter
48
+ this.container = this.app.container;
49
+ }
50
+
51
+ /**
52
+ * Get service instance from container
53
+ */
54
+ get<T>(token: any): T {
55
+ if (!this.container) {
56
+ throw Errors.internal('Application not initialized');
57
+ }
58
+ return this.container.resolve<T>(token);
59
+ }
60
+
61
+ /**
62
+ * Check if service exists in container
63
+ */
64
+ has(token: any): boolean {
65
+ if (!this.container) {
66
+ return false;
67
+ }
68
+ return this.container.has(token);
69
+ }
70
+
71
+ /**
72
+ * Get the application instance
73
+ */
74
+ getApplication(): Application {
75
+ if (!this.app) {
76
+ throw Errors.internal('Application not initialized');
77
+ }
78
+ return this.app;
79
+ }
80
+
81
+ /**
82
+ * Get the container instance
83
+ */
84
+ getContainer(): Container {
85
+ return this.container;
86
+ }
87
+
88
+ /**
89
+ * Register cleanup function
90
+ */
91
+ addCleanup(fn: () => Promise<void> | void): void {
92
+ this.cleanupFns.push(fn);
93
+ }
94
+
95
+ /**
96
+ * Close application and cleanup
97
+ */
98
+ async close(): Promise<void> {
99
+ // Run custom cleanup functions
100
+ for (const fn of this.cleanupFns.reverse()) {
101
+ await fn();
102
+ }
103
+
104
+ // Close application
105
+ if (this.app) {
106
+ await this.app.stop();
107
+ this.app = null;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Create spy for service method
113
+ */
114
+ spyOn<T>(service: T, method: keyof T): jest.SpyInstance {
115
+ const spy = jest.spyOn(service as any, method as any);
116
+ this.addCleanup(() => spy.mockRestore());
117
+ return spy;
118
+ }
119
+
120
+ /**
121
+ * Mock service in container
122
+ */
123
+ mock<T>(token: any, mockImplementation: Partial<T>): void {
124
+ const original = this.container.resolve<T>(token);
125
+ Object.assign(original as any, mockImplementation);
126
+
127
+ this.addCleanup(() => {
128
+ // Restore original implementation
129
+ for (const key in mockImplementation) {
130
+ delete (original as any)[key];
131
+ }
132
+ });
133
+ }
134
+
135
+ /**
136
+ * Override provider in container
137
+ */
138
+ override<T>(token: any, value: T): void {
139
+ const originalBinding = (this.container as any).bindings.get(token);
140
+ (this.container as any).bindings.set(token, {
141
+ token,
142
+ useValue: value,
143
+ scope: 'singleton',
144
+ });
145
+
146
+ this.addCleanup(() => {
147
+ if (originalBinding) {
148
+ (this.container as any).bindings.set(token, originalBinding);
149
+ } else {
150
+ (this.container as any).bindings.delete(token);
151
+ }
152
+ });
153
+ }
154
+ }