@omnitron-dev/testing 0.4.2 → 0.4.4

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 (71) hide show
  1. package/dist/titan/container-utils.d.ts +20 -0
  2. package/dist/titan/container-utils.js +78 -0
  3. package/dist/titan/container-utils.js.map +1 -0
  4. package/dist/titan/database/database-testing.module.d.ts +81 -0
  5. package/dist/titan/database/database-testing.module.js +419 -0
  6. package/dist/titan/database/database-testing.module.js.map +1 -0
  7. package/dist/titan/database/index.d.ts +3 -0
  8. package/dist/titan/database/index.js +4 -0
  9. package/dist/titan/database/index.js.map +1 -0
  10. package/dist/titan/database/test-utilities.d.ts +31 -0
  11. package/dist/titan/database/test-utilities.js +145 -0
  12. package/dist/titan/database/test-utilities.js.map +1 -0
  13. package/dist/titan/index.d.ts +14 -0
  14. package/dist/titan/index.js +10 -0
  15. package/dist/titan/index.js.map +1 -0
  16. package/dist/titan/nexus/index.d.ts +3 -0
  17. package/dist/titan/nexus/index.js +4 -0
  18. package/dist/titan/nexus/index.js.map +1 -0
  19. package/dist/titan/nexus/mock-provider.d.ts +41 -0
  20. package/dist/titan/nexus/mock-provider.js +127 -0
  21. package/dist/titan/nexus/mock-provider.js.map +1 -0
  22. package/dist/titan/nexus/test-container.d.ts +120 -0
  23. package/dist/titan/nexus/test-container.js +559 -0
  24. package/dist/titan/nexus/test-container.js.map +1 -0
  25. package/dist/titan/nexus/test-utilities.d.ts +135 -0
  26. package/dist/titan/nexus/test-utilities.js +484 -0
  27. package/dist/titan/nexus/test-utilities.js.map +1 -0
  28. package/dist/titan/pm/index.d.ts +4 -0
  29. package/dist/titan/pm/index.js +4 -0
  30. package/dist/titan/pm/index.js.map +1 -0
  31. package/dist/titan/pm/mock-process-spawner.d.ts +60 -0
  32. package/dist/titan/pm/mock-process-spawner.js +321 -0
  33. package/dist/titan/pm/mock-process-spawner.js.map +1 -0
  34. package/dist/titan/pm/mock-spawner.d.ts +27 -0
  35. package/dist/titan/pm/mock-spawner.js +99 -0
  36. package/dist/titan/pm/mock-spawner.js.map +1 -0
  37. package/dist/titan/pm/test-process-manager.d.ts +49 -0
  38. package/dist/titan/pm/test-process-manager.js +188 -0
  39. package/dist/titan/pm/test-process-manager.js.map +1 -0
  40. package/dist/titan/redis-test-utils.d.ts +33 -0
  41. package/dist/titan/redis-test-utils.js +415 -0
  42. package/dist/titan/redis-test-utils.js.map +1 -0
  43. package/dist/titan/test-application.d.ts +21 -0
  44. package/dist/titan/test-application.js +90 -0
  45. package/dist/titan/test-application.js.map +1 -0
  46. package/dist/titan/test-fixtures.d.ts +97 -0
  47. package/dist/titan/test-fixtures.js +223 -0
  48. package/dist/titan/test-fixtures.js.map +1 -0
  49. package/dist/titan/test-mocks.d.ts +29 -0
  50. package/dist/titan/test-mocks.js +262 -0
  51. package/dist/titan/test-mocks.js.map +1 -0
  52. package/dist/titan/test-module.d.ts +47 -0
  53. package/dist/titan/test-module.js +120 -0
  54. package/dist/titan/test-module.js.map +1 -0
  55. package/package.json +15 -4
  56. package/src/titan/database/database-testing.module.ts +831 -0
  57. package/src/titan/database/index.ts +30 -0
  58. package/src/titan/database/test-utilities.ts +337 -0
  59. package/src/titan/index.ts +89 -1
  60. package/src/titan/nexus/index.ts +3 -0
  61. package/src/titan/nexus/mock-provider.ts +189 -0
  62. package/src/titan/nexus/test-container.ts +887 -0
  63. package/src/titan/nexus/test-utilities.ts +796 -0
  64. package/src/titan/pm/index.ts +22 -0
  65. package/src/titan/pm/mock-process-spawner.ts +481 -0
  66. package/src/titan/pm/mock-spawner.ts +156 -0
  67. package/src/titan/pm/test-process-manager.ts +345 -0
  68. package/src/titan/redis-test-utils.ts +3 -2
  69. package/src/titan/test-application.ts +2 -2
  70. package/src/titan/test-fixtures.ts +2 -1
  71. package/src/titan/test-module.ts +5 -3
@@ -0,0 +1,796 @@
1
+ import { TestContainer } from './test-container.js';
2
+ import { Container } from '@omnitron-dev/titan/nexus';
3
+ import { createToken, getTokenName } from '@omnitron-dev/titan/nexus';
4
+ import {
5
+ Scope,
6
+ IModule,
7
+ Provider,
8
+ ProviderDefinition,
9
+ Constructor,
10
+ InjectionToken,
11
+ InjectionToken as Token,
12
+ RegistrationOptions,
13
+ } from '@omnitron-dev/titan/nexus';
14
+
15
+ /**
16
+ * Test utility functions for Nexus testing
17
+ */
18
+
19
+ // Jest mock function type
20
+ declare const jest: any;
21
+
22
+ /**
23
+ * Test mock configuration
24
+ */
25
+ export interface TestMockConfig {
26
+ [key: string]: any;
27
+ }
28
+
29
+ /**
30
+ * Provider with explicit token (NestJS style)
31
+ */
32
+ export interface TestProvider<T = any> {
33
+ provide: Token<T>;
34
+ useValue?: T;
35
+ useClass?: Constructor<T>;
36
+ useFactory?: (...args: any[]) => T;
37
+ useToken?: Token<T>;
38
+ inject?: Token<any>[];
39
+ }
40
+
41
+ /**
42
+ * Test module configuration
43
+ */
44
+ export interface TestModuleConfig {
45
+ name: string;
46
+ providers?: (Provider<any> | TestProvider<any>)[];
47
+ mocks?: (Provider<any> | TestProvider<any>)[];
48
+ imports?: IModule[];
49
+ exports?: Token<any>[];
50
+ }
51
+
52
+ /**
53
+ * Test harness configuration
54
+ */
55
+ export interface TestHarnessConfig {
56
+ component?: Constructor<any>;
57
+ providers?: Array<[InjectionToken<any>, ProviderDefinition<any>] | TestProvider<any>>;
58
+ zone?: {
59
+ onEnter?: () => void;
60
+ onLeave?: () => void;
61
+ onError?: (error: Error) => void;
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Test container options with leak detection
67
+ */
68
+ export interface TestContainerOptionsExtended {
69
+ autoMock?: boolean;
70
+ detectLeaks?: boolean;
71
+ trackMemory?: boolean;
72
+ }
73
+
74
+ /**
75
+ * Memory usage info
76
+ */
77
+ export interface MemoryUsage {
78
+ heapUsed: number;
79
+ heapTotal: number;
80
+ objectCount: number;
81
+ }
82
+
83
+ /**
84
+ * Snapshot container for state management
85
+ */
86
+ export class SnapshotContainer extends Container {
87
+ private snapshots = new Map<string, Map<Token<any>, ProviderDefinition<any>>>();
88
+ private snapshotCounter = 0;
89
+ private snapshotStack: string[] = [];
90
+
91
+ snapshot(): string {
92
+ const id = `snapshot_${++this.snapshotCounter}`;
93
+ const state = new Map<Token<any>, ProviderDefinition<any>>();
94
+
95
+ // Capture current registrations
96
+ if ('registrations' in this) {
97
+ const registrations = (this as any).registrations as Map<Token<any>, any>;
98
+ for (const [token, registration] of registrations) {
99
+ if (!Array.isArray(registration)) {
100
+ state.set(token, registration.provider);
101
+ }
102
+ }
103
+ }
104
+
105
+ this.snapshots.set(id, state);
106
+ this.snapshotStack.push(id);
107
+
108
+ return id;
109
+ }
110
+
111
+ restore(snapshotId: string): void {
112
+ const snapshot = this.snapshots.get(snapshotId);
113
+ if (!snapshot) {
114
+ throw new Error(`Snapshot ${snapshotId} not found`);
115
+ }
116
+
117
+ // Clear current registrations and instances completely
118
+ if ('registrations' in this) {
119
+ (this as any).registrations.clear();
120
+ (this as any).instances.clear();
121
+ // Also clear scoped instances
122
+ if ('scopedInstances' in this) {
123
+ (this as any).scopedInstances.clear();
124
+ }
125
+ }
126
+
127
+ // Restore from snapshot
128
+ for (const [token, provider] of snapshot) {
129
+ this.register(token, provider);
130
+ }
131
+
132
+ // Remove from stack
133
+ const stackIndex = this.snapshotStack.indexOf(snapshotId);
134
+ if (stackIndex >= 0) {
135
+ this.snapshotStack.splice(stackIndex);
136
+ }
137
+ }
138
+
139
+ withSnapshot<T>(callback: () => T): T {
140
+ const snapshotId = this.snapshot();
141
+ try {
142
+ return callback();
143
+ } finally {
144
+ this.restore(snapshotId);
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Override register to clear cached instances on override
150
+ */
151
+ override register<T>(
152
+ tokenOrProvider: InjectionToken<T> | Provider<T> | Constructor<T>,
153
+ providerOrOptions?: ProviderDefinition<T> | RegistrationOptions,
154
+ optionsArg?: RegistrationOptions
155
+ ): this {
156
+ // Check if it's an override registration
157
+ const options =
158
+ optionsArg ||
159
+ (typeof providerOrOptions === 'object' &&
160
+ !('useValue' in providerOrOptions) &&
161
+ !('useClass' in providerOrOptions) &&
162
+ !('useFactory' in providerOrOptions) &&
163
+ !('useToken' in providerOrOptions)
164
+ ? (providerOrOptions as RegistrationOptions)
165
+ : undefined);
166
+ if (options?.override && 'instances' in this) {
167
+ // Clear cached instance when overriding
168
+ const token =
169
+ typeof tokenOrProvider === 'object' && 'provide' in tokenOrProvider
170
+ ? tokenOrProvider.provide
171
+ : (tokenOrProvider as InjectionToken<T>);
172
+ (this as any).instances.delete(token);
173
+ }
174
+ return super.register(tokenOrProvider, providerOrOptions as any, optionsArg);
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Isolated container with selective imports
180
+ */
181
+ export class IsolatedContainer extends Container {
182
+ constructor() {
183
+ super();
184
+ }
185
+
186
+ static withImports(source: Container, tokens: Token<any>[]): IsolatedContainer {
187
+ const isolated = new IsolatedContainer();
188
+
189
+ for (const token of tokens) {
190
+ try {
191
+ const value = source.resolve(token);
192
+ isolated.register(token, { useValue: value });
193
+ } catch (error) {
194
+ // Token not available in source
195
+ }
196
+ }
197
+
198
+ return isolated;
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Test module implementation
204
+ */
205
+ export class TestModule implements IModule {
206
+ constructor(
207
+ public readonly name: string,
208
+ public readonly providers: Provider<any>[] = [],
209
+ public readonly imports: IModule[] = [],
210
+ public readonly exports: Token<any>[] = []
211
+ ) {}
212
+
213
+ static override(
214
+ original: IModule,
215
+ overrides: { providers?: Array<Provider<any> | [InjectionToken<any>, Provider<any>]> }
216
+ ): TestModule {
217
+ const providers = overrides.providers || original.providers || [];
218
+
219
+ // Extract tokens from providers for export
220
+ const exports = providers
221
+ .map((p) => {
222
+ if (Array.isArray(p)) {
223
+ return p[0]; // Token is first element of tuple
224
+ }
225
+ // For TestProvider format with 'provide' property
226
+ if (typeof p === 'object' && p && 'provide' in p) {
227
+ return (p as any).provide;
228
+ }
229
+ // For plain providers, we can't extract a token, so skip
230
+ return undefined;
231
+ })
232
+ .filter(Boolean) as Token<any>[];
233
+
234
+ // Combine with original exports
235
+ const originalExports = original.exports || [];
236
+ const allExports = [...new Set([...originalExports, ...exports])];
237
+
238
+ return new TestModule(original.name, providers as any, original.imports || [], allExports);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Test harness for component testing
244
+ */
245
+ export class TestHarness {
246
+ private container: Container;
247
+ private zone?: TestHarnessConfig['zone'];
248
+ private initialized = false;
249
+
250
+ constructor(private config: TestHarnessConfig) {
251
+ this.container = new Container();
252
+ this.zone = config.zone;
253
+ }
254
+
255
+ async initialize(): Promise<void> {
256
+ if (this.config.providers) {
257
+ for (const providerEntry of this.config.providers) {
258
+ if (Array.isArray(providerEntry)) {
259
+ // Tuple format [token, provider]
260
+ const [token, provider] = providerEntry;
261
+ this.container.register(token, provider);
262
+ } else if ('provide' in providerEntry) {
263
+ // TestProvider format
264
+ const token = providerEntry.provide;
265
+ let provider: ProviderDefinition<any>;
266
+
267
+ if ('useValue' in providerEntry && providerEntry.useValue !== undefined) {
268
+ provider = { useValue: providerEntry.useValue };
269
+ } else if ('useClass' in providerEntry && providerEntry.useClass) {
270
+ provider = { useClass: providerEntry.useClass, inject: providerEntry.inject };
271
+ } else if ('useFactory' in providerEntry && providerEntry.useFactory) {
272
+ provider = { useFactory: providerEntry.useFactory, inject: providerEntry.inject };
273
+ } else if ('useToken' in providerEntry && providerEntry.useToken) {
274
+ provider = { useToken: providerEntry.useToken };
275
+ } else {
276
+ throw new Error('Invalid provider configuration');
277
+ }
278
+
279
+ this.container.register(token, provider);
280
+ }
281
+ }
282
+ }
283
+
284
+ this.initialized = true;
285
+ }
286
+
287
+ get<T>(token: Token<T>): T {
288
+ if (!this.initialized) {
289
+ throw new Error('TestHarness not initialized');
290
+ }
291
+ return this.container.resolve(token);
292
+ }
293
+
294
+ async detectChanges(): Promise<void> {
295
+ // Force re-resolution of transient services
296
+ // This is a simplified implementation
297
+ }
298
+
299
+ async runInZone<T>(callback: () => Promise<T>): Promise<T> {
300
+ if (this.zone?.onEnter) {
301
+ this.zone.onEnter();
302
+ }
303
+
304
+ try {
305
+ const result = await callback();
306
+ if (this.zone?.onLeave) {
307
+ this.zone.onLeave();
308
+ }
309
+ return result;
310
+ } catch (error) {
311
+ if (this.zone?.onError) {
312
+ this.zone.onError(error as Error);
313
+ }
314
+ if (this.zone?.onLeave) {
315
+ this.zone.onLeave();
316
+ }
317
+ throw error;
318
+ }
319
+ }
320
+
321
+ async cleanup(): Promise<void> {
322
+ await this.container.dispose();
323
+ this.initialized = false;
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Expectation helpers
329
+ */
330
+ export interface ResolutionExpectation<T> {
331
+ toResolve(): ResolutionExpectation<T>;
332
+ withValue(expected: T): ResolutionExpectation<T>;
333
+ inTime(maxMs: number): Promise<void>;
334
+ }
335
+
336
+ export interface RejectionExpectation {
337
+ toThrow(message?: string): RejectionExpectation;
338
+ withErrorType(errorType: Constructor<Error>): Promise<void>;
339
+ }
340
+
341
+ export interface DependencyExpectation {
342
+ toHaveDependency(token: Token<any>): DependencyExpectation;
343
+ withCardinality(count: number): void;
344
+ }
345
+
346
+ export interface LifecycleExpectation {
347
+ toCallOnInit(): LifecycleExpectation;
348
+ toCallOnDestroy(): Promise<void>;
349
+ }
350
+
351
+ class ResolutionExpectationImpl<T> implements ResolutionExpectation<T> {
352
+ private expectedValue?: T;
353
+ private shouldResolve = false;
354
+ private maxTime?: number;
355
+
356
+ constructor(
357
+ private container: Container,
358
+ private token: Token<T>
359
+ ) {}
360
+
361
+ toResolve(): ResolutionExpectation<T> {
362
+ this.shouldResolve = true;
363
+ return this;
364
+ }
365
+
366
+ withValue(expected: T): ResolutionExpectation<T> {
367
+ this.expectedValue = expected;
368
+ return this;
369
+ }
370
+
371
+ inTime(maxMs: number): Promise<void> {
372
+ this.maxTime = maxMs;
373
+ return this.verify();
374
+ }
375
+
376
+ private async verify(): Promise<void> {
377
+ const start = Date.now();
378
+
379
+ try {
380
+ const result = this.container.resolve(this.token);
381
+
382
+ if (this.expectedValue !== undefined && result !== this.expectedValue) {
383
+ throw new Error(`Expected ${this.expectedValue}, got ${result}`);
384
+ }
385
+
386
+ if (this.maxTime !== undefined) {
387
+ const duration = Date.now() - start;
388
+ if (duration > this.maxTime) {
389
+ throw new Error(`Resolution took ${duration}ms, expected < ${this.maxTime}ms`);
390
+ }
391
+ }
392
+ } catch (error) {
393
+ if (this.shouldResolve) {
394
+ throw error;
395
+ }
396
+ }
397
+ }
398
+ }
399
+
400
+ class RejectionExpectationImpl implements RejectionExpectation {
401
+ private expectedMessage?: string;
402
+ private expectedErrorType?: Constructor<Error>;
403
+
404
+ constructor(
405
+ private container: Container,
406
+ private token: Token<any>
407
+ ) {}
408
+
409
+ toThrow(message?: string): RejectionExpectation {
410
+ this.expectedMessage = message;
411
+ return this;
412
+ }
413
+
414
+ async withErrorType(errorType: Constructor<Error>): Promise<void> {
415
+ this.expectedErrorType = errorType;
416
+ return this.verify();
417
+ }
418
+
419
+ private async verify(): Promise<void> {
420
+ try {
421
+ this.container.resolve(this.token);
422
+ throw new Error('Expected resolution to throw');
423
+ } catch (error) {
424
+ if (this.expectedErrorType && !(error instanceof this.expectedErrorType)) {
425
+ throw new Error(`Expected ${this.expectedErrorType.name}, got ${(error as Error).constructor.name}`);
426
+ }
427
+
428
+ if (this.expectedMessage && !(error as Error).message.includes(this.expectedMessage)) {
429
+ throw new Error(`Expected error message to contain "${this.expectedMessage}"`);
430
+ }
431
+ }
432
+ }
433
+ }
434
+
435
+ class DependencyExpectationImpl implements DependencyExpectation {
436
+ private expectedToken?: Token<any>;
437
+ private expectedCardinality?: number;
438
+
439
+ constructor(
440
+ private container: Container,
441
+ private token: Token<any>
442
+ ) {}
443
+
444
+ toHaveDependency(token: Token<any>): DependencyExpectation {
445
+ this.expectedToken = token;
446
+ return this;
447
+ }
448
+
449
+ withCardinality(count: number): void {
450
+ this.expectedCardinality = count;
451
+ this.verify();
452
+ }
453
+
454
+ private verify(): void {
455
+ // Simplified dependency verification
456
+ if (this.expectedToken) {
457
+ try {
458
+ this.container.resolve(this.expectedToken);
459
+ } catch (error) {
460
+ throw new Error(`Dependency ${String(this.expectedToken)} not found`);
461
+ }
462
+ }
463
+ }
464
+ }
465
+
466
+ class LifecycleExpectationImpl implements LifecycleExpectation {
467
+ private shouldCallOnInit = false;
468
+ private shouldCallOnDestroy = false;
469
+
470
+ constructor(
471
+ private container: Container,
472
+ private token: Token<any>
473
+ ) {}
474
+
475
+ toCallOnInit(): LifecycleExpectation {
476
+ this.shouldCallOnInit = true;
477
+ return this;
478
+ }
479
+
480
+ async toCallOnDestroy(): Promise<void> {
481
+ this.shouldCallOnDestroy = true;
482
+ return this.verify();
483
+ }
484
+
485
+ private async verify(): Promise<void> {
486
+ // Simplified lifecycle verification
487
+ // In a real implementation, you'd track lifecycle method calls
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Wait for async operations to complete
493
+ */
494
+ export async function waitFor(
495
+ condition: () => boolean | Promise<boolean>,
496
+ timeout = 5000,
497
+ interval = 100
498
+ ): Promise<void> {
499
+ const startTime = Date.now();
500
+
501
+ while (Date.now() - startTime < timeout) {
502
+ const result = await condition();
503
+ if (result) {
504
+ return;
505
+ }
506
+ await new Promise((resolve) => setTimeout(resolve, interval));
507
+ }
508
+
509
+ throw new Error(`Timeout waiting for condition after ${timeout}ms`);
510
+ }
511
+
512
+ /**
513
+ * Create a deferred promise for testing async operations
514
+ */
515
+ export function createDeferred<T>(): {
516
+ promise: Promise<T>;
517
+ resolve: (value: T) => void;
518
+ reject: (error: Error) => void;
519
+ } {
520
+ let resolve: (value: T) => void;
521
+ let reject: (error: Error) => void;
522
+
523
+ const promise = new Promise<T>((res, rej) => {
524
+ resolve = res;
525
+ reject = rej;
526
+ });
527
+
528
+ return {
529
+ promise,
530
+ resolve: resolve!,
531
+ reject: reject!,
532
+ };
533
+ }
534
+
535
+ /**
536
+ * Create a test provider
537
+ */
538
+ export function createTestProvider<T>(
539
+ value: T,
540
+ options?: {
541
+ scope?: Scope;
542
+ tags?: string[];
543
+ }
544
+ ): ProviderDefinition<T> {
545
+ return {
546
+ useValue: value,
547
+ scope: options?.scope,
548
+ };
549
+ }
550
+
551
+ /**
552
+ * Create a test factory provider
553
+ */
554
+ export function createTestFactoryProvider<T>(
555
+ factory: (...args: any[]) => T,
556
+ options?: {
557
+ inject?: Token<any>[];
558
+ scope?: Scope;
559
+ tags?: string[];
560
+ }
561
+ ): ProviderDefinition<T> {
562
+ return {
563
+ useFactory: factory,
564
+ inject: options?.inject,
565
+ scope: options?.scope,
566
+ };
567
+ }
568
+
569
+ /**
570
+ * Create a test class provider
571
+ */
572
+ export function createTestClassProvider<T>(
573
+ cls: new (...args: any[]) => T,
574
+ options?: {
575
+ inject?: Token<any>[];
576
+ scope?: Scope;
577
+ tags?: string[];
578
+ }
579
+ ): ProviderDefinition<T> {
580
+ return {
581
+ useClass: cls,
582
+ inject: options?.inject,
583
+ scope: options?.scope,
584
+ };
585
+ }
586
+
587
+ /**
588
+ * Assert that a function throws a specific error
589
+ */
590
+ export async function assertThrows<E extends Error>(
591
+ fn: () => any | Promise<any>,
592
+ errorType?: new (...args: any[]) => E,
593
+ message?: string | RegExp
594
+ ): Promise<E> {
595
+ try {
596
+ await fn();
597
+ throw new Error('Expected function to throw');
598
+ } catch (error) {
599
+ if (errorType && !(error instanceof errorType)) {
600
+ throw new Error(`Expected error of type ${errorType.name}, got ${(error as Error).constructor.name}`);
601
+ }
602
+
603
+ if (message) {
604
+ const errorMessage = (error as Error).message;
605
+ if (typeof message === 'string') {
606
+ if (!errorMessage.includes(message)) {
607
+ throw new Error(`Expected error message to include "${message}", got "${errorMessage}"`);
608
+ }
609
+ } else if (message instanceof RegExp) {
610
+ if (!message.test(errorMessage)) {
611
+ throw new Error(`Expected error message to match ${message}, got "${errorMessage}"`);
612
+ }
613
+ }
614
+ }
615
+
616
+ return error as E;
617
+ }
618
+ }
619
+
620
+ /**
621
+ * Create a test token with metadata
622
+ */
623
+ export function createTestToken<T>(name: string, metadata?: Record<string, any>): Token<T> {
624
+ return createToken<T>(name, metadata);
625
+ }
626
+
627
+ /**
628
+ * Verify container state
629
+ */
630
+ export function verifyContainerState(
631
+ container: TestContainer,
632
+ expectations: {
633
+ registeredTokens?: Token<any>[];
634
+ resolvedTokens?: Token<any>[];
635
+ mocks?: Token<any>[];
636
+ spies?: Array<{ token: Token<any>; method: string }>;
637
+ }
638
+ ): void {
639
+ const metadata = container.getTestMetadata();
640
+
641
+ if (expectations.registeredTokens) {
642
+ for (const token of expectations.registeredTokens) {
643
+ // Check if token is registered
644
+ try {
645
+ container.resolve(token);
646
+ } catch {
647
+ // Token might not be resolvable but could be registered
648
+ }
649
+ }
650
+ }
651
+
652
+ if (expectations.resolvedTokens) {
653
+ for (const token of expectations.resolvedTokens) {
654
+ try {
655
+ container.resolve(token);
656
+ } catch {
657
+ throw new Error(`Expected token ${getTokenName(token)} to be resolvable`);
658
+ }
659
+ }
660
+ }
661
+
662
+ if (expectations.mocks) {
663
+ for (const token of expectations.mocks) {
664
+ try {
665
+ container.getMock(token);
666
+ } catch {
667
+ throw new Error(`Expected token ${getTokenName(token)} to have a mock`);
668
+ }
669
+ }
670
+ }
671
+
672
+ if (expectations.spies) {
673
+ for (const { token, method } of expectations.spies) {
674
+ try {
675
+ container.getSpy(token, method as any);
676
+ } catch {
677
+ throw new Error(`Expected token ${getTokenName(token)} to have a spy for method ${method}`);
678
+ }
679
+ }
680
+ }
681
+ }
682
+
683
+ /**
684
+ * Clean up test resources
685
+ */
686
+ export function cleanupTest(container: TestContainer): void {
687
+ container.resetMocks();
688
+ container.clearMocks();
689
+ container.clearInteractions();
690
+ container.dispose();
691
+ }
692
+
693
+ /**
694
+ * Create a test suite helper
695
+ */
696
+ export function createTestSuite(
697
+ name: string,
698
+ setup: () => TestContainer | Promise<TestContainer>
699
+ ): {
700
+ container: TestContainer;
701
+ beforeEach: () => Promise<void>;
702
+ afterEach: () => void;
703
+ } {
704
+ let container: TestContainer;
705
+
706
+ return {
707
+ get container() {
708
+ return container;
709
+ },
710
+
711
+ async beforeEach() {
712
+ container = await setup();
713
+ },
714
+
715
+ afterEach() {
716
+ if (container) {
717
+ cleanupTest(container);
718
+ }
719
+ },
720
+ };
721
+ }
722
+
723
+ /**
724
+ * Create test module
725
+ */
726
+ export function createTestModule(config: TestModuleConfig): TestModule {
727
+ // Convert TestProvider format to tuple format and collect tokens
728
+ const allProviders: Array<[Token<any>, ProviderDefinition<any>]> = [];
729
+ const tokens: Token<any>[] = [];
730
+
731
+ const processProviders = (providers: (Provider<any> | TestProvider<any>)[] | undefined) => {
732
+ if (!providers) return;
733
+
734
+ for (const provider of providers) {
735
+ if ('provide' in provider) {
736
+ // TestProvider format - extract token and convert to regular provider
737
+ const token = provider.provide;
738
+ tokens.push(token);
739
+
740
+ let regularProvider: ProviderDefinition<any>;
741
+ if ('useValue' in provider && provider.useValue !== undefined) {
742
+ regularProvider = { useValue: provider.useValue };
743
+ } else if ('useClass' in provider && provider.useClass) {
744
+ regularProvider = { useClass: provider.useClass, inject: provider.inject };
745
+ } else if ('useFactory' in provider && provider.useFactory) {
746
+ regularProvider = { useFactory: provider.useFactory, inject: provider.inject };
747
+ } else if ('useToken' in provider && provider.useToken) {
748
+ regularProvider = { useToken: provider.useToken };
749
+ } else {
750
+ throw new Error('Invalid provider configuration');
751
+ }
752
+
753
+ allProviders.push([token, regularProvider]);
754
+ } else {
755
+ // Regular Provider format - can't extract token automatically
756
+ // This is a limitation - regular providers need explicit exports
757
+ allProviders.push(provider as any);
758
+ }
759
+ }
760
+ };
761
+
762
+ processProviders(config.providers);
763
+ processProviders(config.mocks);
764
+
765
+ // Use provided exports or auto-export collected tokens
766
+ const exports = config.exports || tokens;
767
+
768
+ // Create the module with providers in tuple format
769
+ return new TestModule(config.name, allProviders as any, config.imports, exports as Token<any>[]);
770
+ }
771
+
772
+ /**
773
+ * Create test harness
774
+ */
775
+ export function createTestHarness(config: TestHarnessConfig): TestHarness {
776
+ return new TestHarness(config);
777
+ }
778
+
779
+ /**
780
+ * Expectation helper functions
781
+ */
782
+ export function expectResolution<T>(container: Container, token: Token<T>): ResolutionExpectation<T> {
783
+ return new ResolutionExpectationImpl(container, token);
784
+ }
785
+
786
+ export function expectRejection(container: Container, token: Token<any>): RejectionExpectation {
787
+ return new RejectionExpectationImpl(container, token);
788
+ }
789
+
790
+ export function expectDependency(container: Container, token: Token<any>): DependencyExpectation {
791
+ return new DependencyExpectationImpl(container, token);
792
+ }
793
+
794
+ export function expectLifecycle(container: Container, token: Token<any>): LifecycleExpectation {
795
+ return new LifecycleExpectationImpl(container, token);
796
+ }