@omnitron-dev/testing 0.1.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -0
  3. package/dist/async/deferred.d.ts +15 -0
  4. package/dist/async/deferred.js +35 -0
  5. package/dist/async/deferred.js.map +1 -0
  6. package/dist/async/events.d.ts +32 -0
  7. package/dist/async/events.js +176 -0
  8. package/dist/async/events.js.map +1 -0
  9. package/dist/async/index.d.ts +5 -0
  10. package/dist/async/index.js +6 -0
  11. package/dist/async/index.js.map +1 -0
  12. package/dist/async/mock-timer.d.ts +19 -0
  13. package/dist/async/mock-timer.js +87 -0
  14. package/dist/async/mock-timer.js.map +1 -0
  15. package/dist/async/retry.d.ts +8 -0
  16. package/dist/async/retry.js +36 -0
  17. package/dist/async/retry.js.map +1 -0
  18. package/dist/async/wait.d.ts +10 -0
  19. package/dist/async/wait.js +35 -0
  20. package/dist/async/wait.js.map +1 -0
  21. package/dist/docker/database-manager.d.ts +22 -0
  22. package/dist/docker/database-manager.js +97 -0
  23. package/dist/docker/database-manager.js.map +1 -0
  24. package/dist/docker/docker-test-manager.d.ts +44 -0
  25. package/dist/docker/docker-test-manager.js +812 -0
  26. package/dist/docker/docker-test-manager.js.map +1 -0
  27. package/dist/docker/index.d.ts +4 -0
  28. package/dist/docker/index.js +4 -0
  29. package/dist/docker/index.js.map +1 -0
  30. package/dist/docker/redis-manager.d.ts +12 -0
  31. package/dist/docker/redis-manager.js +452 -0
  32. package/dist/docker/redis-manager.js.map +1 -0
  33. package/dist/docker/types.d.ts +103 -0
  34. package/dist/docker/types.js +2 -0
  35. package/dist/docker/types.js.map +1 -0
  36. package/dist/errors.d.ts +15 -0
  37. package/dist/errors.js +28 -0
  38. package/dist/errors.js.map +1 -0
  39. package/dist/helpers/assertions.d.ts +6 -0
  40. package/dist/helpers/assertions.js +37 -0
  41. package/dist/helpers/assertions.js.map +1 -0
  42. package/dist/helpers/console.d.ts +1 -0
  43. package/dist/helpers/console.js +23 -0
  44. package/dist/helpers/console.js.map +1 -0
  45. package/dist/helpers/index.d.ts +3 -0
  46. package/dist/helpers/index.js +4 -0
  47. package/dist/helpers/index.js.map +1 -0
  48. package/dist/helpers/temp-dir.d.ts +2 -0
  49. package/dist/helpers/temp-dir.js +13 -0
  50. package/dist/helpers/temp-dir.js.map +1 -0
  51. package/dist/index.d.ts +18 -0
  52. package/dist/index.js +22 -0
  53. package/dist/index.js.map +1 -0
  54. package/dist/performance/index.d.ts +2 -0
  55. package/dist/performance/index.js +3 -0
  56. package/dist/performance/index.js.map +1 -0
  57. package/dist/performance/memory-detector.d.ts +9 -0
  58. package/dist/performance/memory-detector.js +61 -0
  59. package/dist/performance/memory-detector.js.map +1 -0
  60. package/dist/performance/perf-timer.d.ts +9 -0
  61. package/dist/performance/perf-timer.js +49 -0
  62. package/dist/performance/perf-timer.js.map +1 -0
  63. package/dist/runtime/bun-adapter.d.ts +1 -0
  64. package/dist/runtime/bun-adapter.js +100 -0
  65. package/dist/runtime/bun-adapter.js.map +1 -0
  66. package/dist/runtime/deno-adapter.d.ts +27 -0
  67. package/dist/runtime/deno-adapter.js +221 -0
  68. package/dist/runtime/deno-adapter.js.map +1 -0
  69. package/dist/runtime/node-adapter.d.ts +16 -0
  70. package/dist/runtime/node-adapter.js +30 -0
  71. package/dist/runtime/node-adapter.js.map +1 -0
  72. package/dist/runtime/test-adapter.d.ts +22 -0
  73. package/dist/runtime/test-adapter.js +93 -0
  74. package/dist/runtime/test-adapter.js.map +1 -0
  75. package/dist/titan/container-utils.d.ts +20 -0
  76. package/dist/titan/container-utils.js +78 -0
  77. package/dist/titan/container-utils.js.map +1 -0
  78. package/dist/titan/database/database-testing.module.d.ts +82 -0
  79. package/dist/titan/database/database-testing.module.js +433 -0
  80. package/dist/titan/database/database-testing.module.js.map +1 -0
  81. package/dist/titan/database/index.d.ts +3 -0
  82. package/dist/titan/database/index.js +4 -0
  83. package/dist/titan/database/index.js.map +1 -0
  84. package/dist/titan/database/test-utilities.d.ts +31 -0
  85. package/dist/titan/database/test-utilities.js +146 -0
  86. package/dist/titan/database/test-utilities.js.map +1 -0
  87. package/dist/titan/index.d.ts +14 -0
  88. package/dist/titan/index.js +10 -0
  89. package/dist/titan/index.js.map +1 -0
  90. package/dist/titan/nexus/index.d.ts +3 -0
  91. package/dist/titan/nexus/index.js +4 -0
  92. package/dist/titan/nexus/index.js.map +1 -0
  93. package/dist/titan/nexus/mock-provider.d.ts +41 -0
  94. package/dist/titan/nexus/mock-provider.js +127 -0
  95. package/dist/titan/nexus/mock-provider.js.map +1 -0
  96. package/dist/titan/nexus/test-container.d.ts +120 -0
  97. package/dist/titan/nexus/test-container.js +559 -0
  98. package/dist/titan/nexus/test-container.js.map +1 -0
  99. package/dist/titan/nexus/test-utilities.d.ts +135 -0
  100. package/dist/titan/nexus/test-utilities.js +484 -0
  101. package/dist/titan/nexus/test-utilities.js.map +1 -0
  102. package/dist/titan/pm/index.d.ts +4 -0
  103. package/dist/titan/pm/index.js +4 -0
  104. package/dist/titan/pm/index.js.map +1 -0
  105. package/dist/titan/pm/mock-process-spawner.d.ts +61 -0
  106. package/dist/titan/pm/mock-process-spawner.js +343 -0
  107. package/dist/titan/pm/mock-process-spawner.js.map +1 -0
  108. package/dist/titan/pm/mock-spawner.d.ts +28 -0
  109. package/dist/titan/pm/mock-spawner.js +101 -0
  110. package/dist/titan/pm/mock-spawner.js.map +1 -0
  111. package/dist/titan/pm/test-process-manager.d.ts +49 -0
  112. package/dist/titan/pm/test-process-manager.js +192 -0
  113. package/dist/titan/pm/test-process-manager.js.map +1 -0
  114. package/dist/titan/redis-test-utils.d.ts +33 -0
  115. package/dist/titan/redis-test-utils.js +415 -0
  116. package/dist/titan/redis-test-utils.js.map +1 -0
  117. package/dist/titan/test-application.d.ts +21 -0
  118. package/dist/titan/test-application.js +90 -0
  119. package/dist/titan/test-application.js.map +1 -0
  120. package/dist/titan/test-fixtures.d.ts +97 -0
  121. package/dist/titan/test-fixtures.js +223 -0
  122. package/dist/titan/test-fixtures.js.map +1 -0
  123. package/dist/titan/test-mocks.d.ts +30 -0
  124. package/dist/titan/test-mocks.js +262 -0
  125. package/dist/titan/test-mocks.js.map +1 -0
  126. package/dist/titan/test-module.d.ts +47 -0
  127. package/dist/titan/test-module.js +120 -0
  128. package/dist/titan/test-module.js.map +1 -0
  129. package/package.json +146 -0
  130. package/runtime/bun.d.ts +2 -0
  131. package/runtime/bun.js +5 -0
  132. package/runtime/bun.ts +7 -0
  133. package/runtime/deno.d.ts +2 -0
  134. package/runtime/deno.js +4 -0
  135. package/runtime/vitest.d.ts +2 -0
  136. package/runtime/vitest.js +16 -0
  137. package/runtime/vitest.ts +7 -0
  138. package/src/async/README.md +336 -0
  139. package/src/async/deferred.ts +98 -0
  140. package/src/async/events.ts +386 -0
  141. package/src/async/index.ts +23 -0
  142. package/src/async/mock-timer.ts +220 -0
  143. package/src/async/retry.ts +115 -0
  144. package/src/async/wait.ts +148 -0
  145. package/src/docker/database-manager.ts +242 -0
  146. package/src/docker/docker-test-manager.ts +1198 -0
  147. package/src/docker/index.ts +48 -0
  148. package/src/docker/redis-manager.ts +741 -0
  149. package/src/docker/types.ts +216 -0
  150. package/src/errors.ts +38 -0
  151. package/src/globals.d.ts +24 -0
  152. package/src/helpers/assertions.ts +168 -0
  153. package/src/helpers/console.ts +74 -0
  154. package/src/helpers/index.ts +15 -0
  155. package/src/helpers/temp-dir.ts +50 -0
  156. package/src/index.ts +43 -0
  157. package/src/performance/index.ts +11 -0
  158. package/src/performance/memory-detector.ts +166 -0
  159. package/src/performance/perf-timer.ts +146 -0
  160. package/src/runtime/bun-adapter.ts +127 -0
  161. package/src/runtime/deno-adapter.ts +286 -0
  162. package/src/runtime/node-adapter.ts +40 -0
  163. package/src/runtime/test-adapter.test.ts +98 -0
  164. package/src/runtime/test-adapter.ts +122 -0
  165. package/src/titan/container-utils.ts +128 -0
  166. package/src/titan/database/database-testing.module.ts +851 -0
  167. package/src/titan/database/index.ts +30 -0
  168. package/src/titan/database/test-utilities.ts +340 -0
  169. package/src/titan/index.ts +128 -0
  170. package/src/titan/nexus/index.ts +3 -0
  171. package/src/titan/nexus/mock-provider.ts +189 -0
  172. package/src/titan/nexus/test-container.ts +895 -0
  173. package/src/titan/nexus/test-utilities.ts +797 -0
  174. package/src/titan/pm/index.ts +22 -0
  175. package/src/titan/pm/mock-process-spawner.ts +534 -0
  176. package/src/titan/pm/mock-spawner.ts +162 -0
  177. package/src/titan/pm/test-process-manager.ts +352 -0
  178. package/src/titan/redis-test-utils.ts +567 -0
  179. package/src/titan/test-application.ts +154 -0
  180. package/src/titan/test-fixtures.ts +304 -0
  181. package/src/titan/test-mocks.ts +336 -0
  182. package/src/titan/test-module.ts +233 -0
@@ -0,0 +1,895 @@
1
+ /**
2
+ * Testing utilities for Nexus DI Container
3
+ */
4
+
5
+ import { Container } from '@omnitron-dev/titan/nexus';
6
+ import {
7
+ IModule,
8
+ Provider,
9
+ ProviderDefinition,
10
+ Constructor,
11
+ InjectionToken,
12
+ RegistrationOptions,
13
+ } from '@omnitron-dev/titan/nexus';
14
+
15
+ /**
16
+ * Mock provider configuration
17
+ */
18
+ export interface MockConfig<T = any> {
19
+ token: InjectionToken<T>;
20
+ mock: Partial<T> | T;
21
+ spy?: boolean;
22
+ }
23
+
24
+ /**
25
+ * Test container options
26
+ */
27
+ export interface TestContainerOptions {
28
+ modules?: IModule[];
29
+ providers?: Array<[InjectionToken<any>, ProviderDefinition<any>]>;
30
+ mocks?: MockConfig[];
31
+ autoMock?: boolean;
32
+ isolate?: boolean;
33
+ detectLeaks?: boolean;
34
+ trackMemory?: boolean;
35
+ }
36
+
37
+ /**
38
+ * Interaction record for testing
39
+ */
40
+ export interface Interaction {
41
+ method: string;
42
+ args: any[];
43
+ result?: any;
44
+ error?: Error;
45
+ timestamp?: number;
46
+ }
47
+
48
+ /**
49
+ * Spy expectation interface
50
+ */
51
+ export interface SpyExpectation {
52
+ verify(spy: any): boolean;
53
+ getMessage(): string;
54
+ }
55
+
56
+ /**
57
+ * Call count expectation
58
+ */
59
+ export class CallCountExpectation implements SpyExpectation {
60
+ constructor(
61
+ private expectedCount: number,
62
+ private comparison: 'exact' | 'atleast' | 'atmost' = 'exact'
63
+ ) {}
64
+
65
+ verify(spy: any): boolean {
66
+ const actualCount = spy.mock.calls.length;
67
+ switch (this.comparison) {
68
+ case 'exact':
69
+ return actualCount === this.expectedCount;
70
+ case 'atleast':
71
+ return actualCount >= this.expectedCount;
72
+ case 'atmost':
73
+ return actualCount <= this.expectedCount;
74
+ default:
75
+ return false;
76
+ }
77
+ }
78
+
79
+ getMessage(): string {
80
+ switch (this.comparison) {
81
+ case 'exact':
82
+ return `Expected exactly ${this.expectedCount} calls`;
83
+ case 'atleast':
84
+ return `Expected at least ${this.expectedCount} calls`;
85
+ case 'atmost':
86
+ return `Expected at most ${this.expectedCount} calls`;
87
+ default:
88
+ return 'Unknown comparison';
89
+ }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Call arguments expectation
95
+ */
96
+ export class CallArgumentsExpectation implements SpyExpectation {
97
+ constructor(
98
+ private expectedArgs: any[],
99
+ private callIndex: number = 0
100
+ ) {}
101
+
102
+ verify(spy: any): boolean {
103
+ const calls = spy.mock.calls;
104
+ if (calls.length <= this.callIndex) {
105
+ return false;
106
+ }
107
+
108
+ const actualArgs = calls[this.callIndex];
109
+ if (actualArgs.length !== this.expectedArgs.length) {
110
+ return false;
111
+ }
112
+
113
+ return this.expectedArgs.every((expected, index) => {
114
+ const actual = actualArgs[index];
115
+ if (typeof expected === 'object' && expected !== null) {
116
+ return JSON.stringify(actual) === JSON.stringify(expected);
117
+ }
118
+ return actual === expected;
119
+ });
120
+ }
121
+
122
+ getMessage(): string {
123
+ return `Expected call ${this.callIndex} with arguments ${JSON.stringify(this.expectedArgs)}`;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Never called expectation
129
+ */
130
+ export class NeverCalledExpectation implements SpyExpectation {
131
+ verify(spy: any): boolean {
132
+ return spy.mock.calls.length === 0;
133
+ }
134
+
135
+ getMessage(): string {
136
+ return 'Expected spy to never be called';
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Test container with testing utilities
142
+ */
143
+ // Vitest types workaround for build
144
+ declare const vi: any;
145
+
146
+ export class TestContainer extends Container {
147
+ private mocks = new Map<InjectionToken<any>, any>();
148
+ private spies = new Map<InjectionToken<any>, Map<string, any>>();
149
+ private interactions = new Map<InjectionToken<any>, Interaction[]>();
150
+ private snapshots = new Map<string, Map<InjectionToken<any>, any>>();
151
+ private expectations = new Map<InjectionToken<any>, Map<string, SpyExpectation[]>>();
152
+ private autoMock: boolean;
153
+ private originalContainer?: Container;
154
+ private detectLeaks: boolean;
155
+ private trackMemory: boolean;
156
+ private resolvedTokens = new Set<InjectionToken<any>>();
157
+ private registeredTokens = new Set<InjectionToken<any>>();
158
+ private initialObjectCount = 0;
159
+
160
+ constructor(options: TestContainerOptions = {}) {
161
+ super(options.isolate ? undefined : undefined);
162
+
163
+ this.autoMock = options.autoMock || false;
164
+ this.detectLeaks = options.detectLeaks || false;
165
+ this.trackMemory = options.trackMemory || false;
166
+
167
+ // Set initial object count baseline
168
+ if (this.trackMemory) {
169
+ this.initialObjectCount = this.getObjectCount();
170
+ }
171
+
172
+ // Load modules
173
+ if (options.modules) {
174
+ for (const module of options.modules) {
175
+ this.loadModule(module);
176
+ }
177
+ }
178
+
179
+ // Register providers
180
+ if (options.providers) {
181
+ for (const [token, provider] of options.providers) {
182
+ this.register(token, provider);
183
+ }
184
+ }
185
+
186
+ // Setup mocks
187
+ if (options.mocks) {
188
+ for (const mockConfig of options.mocks) {
189
+ this.mock(mockConfig.token, mockConfig.mock, mockConfig.spy);
190
+ }
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Mock a dependency
196
+ */
197
+ mock<T>(token: InjectionToken<T>, mockValue: Partial<T> | T, spy = false): this {
198
+ const mock = this.createMock(mockValue, spy);
199
+ this.mocks.set(token, mock);
200
+
201
+ // Track registered token
202
+ if (this.detectLeaks) {
203
+ this.registeredTokens.add(token);
204
+ }
205
+
206
+ // Create interaction-recording wrapper
207
+ const wrappedMock = this.wrapWithInteractionRecording(token, mock);
208
+
209
+ // Override registration
210
+ this.register(token, { useValue: wrappedMock }, { tags: ['override'] });
211
+
212
+ if (spy) {
213
+ this.setupSpies(token, wrappedMock);
214
+ }
215
+
216
+ return this;
217
+ }
218
+
219
+ /**
220
+ * Create a mock object
221
+ */
222
+ private createMock<T>(value: Partial<T> | T, spy: boolean): T {
223
+ if (typeof value !== 'object' || value === null) {
224
+ return value as T;
225
+ }
226
+
227
+ // If no spy is needed, return the original object to preserve reference equality
228
+ if (!spy) {
229
+ return value as T;
230
+ }
231
+
232
+ // Only create a copy when spy is enabled
233
+ const mock = { ...value } as any;
234
+
235
+ // Auto-mock functions if spy is enabled
236
+ for (const key in mock) {
237
+ if (typeof mock[key] === 'function') {
238
+ const original = mock[key];
239
+ mock[key] = vi.fn(original);
240
+ }
241
+ }
242
+
243
+ return mock;
244
+ }
245
+
246
+ /**
247
+ * Wrap mock with interaction recording
248
+ */
249
+ private wrapWithInteractionRecording<T>(token: InjectionToken<T>, mock: T): T {
250
+ if (typeof mock !== 'object' || mock === null) {
251
+ return mock;
252
+ }
253
+
254
+ const wrapped = { ...mock } as any;
255
+
256
+ // Wrap functions to record interactions
257
+ for (const key in wrapped) {
258
+ if (typeof wrapped[key] === 'function') {
259
+ const originalFn = wrapped[key];
260
+ wrapped[key] = vi.fn((...args: any[]) => {
261
+ try {
262
+ const result = originalFn(...args);
263
+ this.recordInteraction(token, {
264
+ method: key,
265
+ args,
266
+ });
267
+ return result;
268
+ } catch (error) {
269
+ this.recordInteraction(token, {
270
+ method: key,
271
+ args,
272
+ error: error as Error,
273
+ });
274
+ throw error;
275
+ }
276
+ });
277
+ }
278
+ }
279
+
280
+ return wrapped;
281
+ }
282
+
283
+ /**
284
+ * Setup spies for a mock
285
+ */
286
+ private setupSpies<T>(token: InjectionToken<T>, mock: T): void {
287
+ const spyMap = new Map<string, any>();
288
+
289
+ for (const key in mock as any) {
290
+ const value = (mock as any)[key];
291
+ if (typeof value === 'function' && vi.isMockFunction(value)) {
292
+ spyMap.set(key, value);
293
+ }
294
+ }
295
+
296
+ this.spies.set(token, spyMap);
297
+ }
298
+
299
+ /**
300
+ * Spy on a method
301
+ */
302
+ spy<T>(token: InjectionToken<T>, method: keyof T): any {
303
+ const instance = this.resolve(token);
304
+
305
+ if (!instance || typeof instance[method] !== 'function') {
306
+ throw new Error(`Cannot spy on ${String(method)} of ${String(token)}`);
307
+ }
308
+
309
+ const spy = vi.spyOn(instance as any, method as string);
310
+
311
+ let spyMap = this.spies.get(token);
312
+ if (!spyMap) {
313
+ spyMap = new Map();
314
+ this.spies.set(token, spyMap);
315
+ }
316
+
317
+ spyMap.set(method as string, spy);
318
+
319
+ return spy;
320
+ }
321
+
322
+ /**
323
+ * Stub a dependency
324
+ */
325
+ stub<T>(token: InjectionToken<T>, stub: Partial<T> | T): this {
326
+ // Create a stub object where each property returns the specified value
327
+ const stubObject = {} as any;
328
+ const stubAsAny = stub as any;
329
+
330
+ for (const key in stubAsAny) {
331
+ const value = stubAsAny[key];
332
+ if (typeof value === 'function') {
333
+ // If the stub value is already a function, use it directly
334
+ stubObject[key] = value;
335
+ } else {
336
+ // Otherwise, create a function that returns the value
337
+ stubObject[key] = vi.fn(() => value);
338
+ }
339
+ }
340
+
341
+ this.register(token, { useValue: stubObject }, { tags: ['override'] });
342
+ return this;
343
+ }
344
+
345
+ /**
346
+ * Override a registration
347
+ */
348
+ override<T>(token: InjectionToken<T>): {
349
+ useValue: (value: T) => TestContainer;
350
+ useClass: (cls: Constructor<T>) => TestContainer;
351
+ useFactory: (factory: (...args: any[]) => T) => TestContainer;
352
+ } {
353
+ return {
354
+ useValue: (value: T) => {
355
+ this.register(token, { useValue: value }, { override: true, tags: ['override'] });
356
+ return this;
357
+ },
358
+ useClass: (cls: Constructor<T>) => {
359
+ this.register(token, { useClass: cls }, { override: true, tags: ['override'] });
360
+ return this;
361
+ },
362
+ useFactory: (factory: (...args: any[]) => T) => {
363
+ this.register(token, { useFactory: factory }, { override: true, tags: ['override'] });
364
+ return this;
365
+ },
366
+ };
367
+ }
368
+
369
+ /**
370
+ * Get mock instance
371
+ */
372
+ getMock<T>(token: InjectionToken<T>): T {
373
+ const mock = this.mocks.get(token);
374
+ if (!mock) {
375
+ throw new Error(`No mock found for ${String(token)}`);
376
+ }
377
+ return mock;
378
+ }
379
+
380
+ /**
381
+ * Get spy instance
382
+ */
383
+ getSpy<T>(token: InjectionToken<T>, method: keyof T): any {
384
+ const spyMap = this.spies.get(token);
385
+ const spy = spyMap?.get(method as string);
386
+
387
+ if (!spy) {
388
+ throw new Error(`No spy found for ${String(method)} of ${String(token)}`);
389
+ }
390
+
391
+ return spy;
392
+ }
393
+
394
+ /**
395
+ * Record interaction
396
+ */
397
+ recordInteraction(token: InjectionToken<any>, interaction: Interaction): void {
398
+ let interactions = this.interactions.get(token);
399
+ if (!interactions) {
400
+ interactions = [];
401
+ this.interactions.set(token, interactions);
402
+ }
403
+ interactions.push(interaction);
404
+ }
405
+
406
+ /**
407
+ * Get interactions
408
+ */
409
+ getInteractions(token: InjectionToken<any>): Interaction[] {
410
+ const interactions = this.interactions.get(token) || [];
411
+ // Return interactions - if result/error/timestamp are undefined, they will be omitted
412
+ return interactions.map(({ method, args, result, error, timestamp }) => {
413
+ const interaction: Interaction = { method, args };
414
+ if (result !== undefined) interaction.result = result;
415
+ if (error !== undefined) interaction.error = error;
416
+ if (timestamp !== undefined) interaction.timestamp = timestamp;
417
+ return interaction;
418
+ });
419
+ }
420
+
421
+ /**
422
+ * Clear interactions
423
+ */
424
+ clearInteractions(token?: InjectionToken<any>): void {
425
+ if (token) {
426
+ this.interactions.delete(token);
427
+ } else {
428
+ this.interactions.clear();
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Take a snapshot of container state
434
+ */
435
+ snapshot(name = 'default'): void {
436
+ const snapshot = new Map<InjectionToken<any>, any>();
437
+
438
+ // Snapshot mocks
439
+ for (const [token, mock] of this.mocks) {
440
+ snapshot.set(token, { ...mock });
441
+ }
442
+
443
+ this.snapshots.set(name, snapshot);
444
+ }
445
+
446
+ /**
447
+ * Restore from snapshot or to original state
448
+ */
449
+ restore(name?: string): void {
450
+ if (name === undefined) {
451
+ // Restore to original state - clear all overrides
452
+ if ('registrations' in this) {
453
+ (this as any).registrations.clear();
454
+ (this as any).instances.clear();
455
+ }
456
+
457
+ this.mocks.clear();
458
+ this.spies.clear();
459
+ this.interactions.clear();
460
+ return;
461
+ }
462
+
463
+ const snapshot = this.snapshots.get(name);
464
+ if (!snapshot) {
465
+ throw new Error(`Snapshot '${name}' not found`);
466
+ }
467
+
468
+ // Restore mocks
469
+ for (const [token, mockSnapshot] of snapshot) {
470
+ const mock = this.mocks.get(token);
471
+ if (mock) {
472
+ Object.assign(mock, mockSnapshot);
473
+ }
474
+ }
475
+
476
+ // Clear spies
477
+ for (const spyMap of this.spies.values()) {
478
+ for (const spy of spyMap.values()) {
479
+ spy.mockRestore();
480
+ }
481
+ }
482
+ this.spies.clear();
483
+
484
+ // Clear interactions
485
+ this.interactions.clear();
486
+ }
487
+
488
+ /**
489
+ * Reset all mocks and spies
490
+ */
491
+ resetMocks(): void {
492
+ // Reset regular mocks
493
+ for (const mock of this.mocks.values()) {
494
+ if (mock && typeof mock === 'object') {
495
+ for (const key in mock) {
496
+ const value = mock[key];
497
+ if (value && vi.isMockFunction && vi.isMockFunction(value)) {
498
+ value.mockReset();
499
+ }
500
+ }
501
+ }
502
+ }
503
+
504
+ // Reset spies
505
+ for (const spyMap of this.spies.values()) {
506
+ for (const spy of spyMap.values()) {
507
+ if (spy && spy.mockReset) {
508
+ spy.mockReset();
509
+ }
510
+ }
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Clear all mocks
516
+ */
517
+ clearMocks(): void {
518
+ for (const spyMap of this.spies.values()) {
519
+ for (const spy of spyMap.values()) {
520
+ spy.mockClear();
521
+ }
522
+ }
523
+ }
524
+
525
+ /**
526
+ * Add expectation for a spy
527
+ */
528
+ expect<T>(
529
+ token: InjectionToken<T>,
530
+ method: keyof T
531
+ ): {
532
+ toBeCalledTimes: (count: number) => void;
533
+ toBeCalledWith: (...args: any[]) => void;
534
+ toBeCalledAtLeast: (count: number) => void;
535
+ toBeCalledAtMost: (count: number) => void;
536
+ neverBeCalled: () => void;
537
+ } {
538
+ const methodName = method as string;
539
+
540
+ return {
541
+ toBeCalledTimes: (count: number) => {
542
+ this.addExpectation(token, methodName, new CallCountExpectation(count, 'exact'));
543
+ },
544
+ toBeCalledWith: (...args: any[]) => {
545
+ this.addExpectation(token, methodName, new CallArgumentsExpectation(args));
546
+ },
547
+ toBeCalledAtLeast: (count: number) => {
548
+ this.addExpectation(token, methodName, new CallCountExpectation(count, 'atleast'));
549
+ },
550
+ toBeCalledAtMost: (count: number) => {
551
+ this.addExpectation(token, methodName, new CallCountExpectation(count, 'atmost'));
552
+ },
553
+ neverBeCalled: () => {
554
+ this.addExpectation(token, methodName, new NeverCalledExpectation());
555
+ },
556
+ };
557
+ }
558
+
559
+ /**
560
+ * Add an expectation
561
+ */
562
+ private addExpectation(token: InjectionToken<any>, method: string, expectation: SpyExpectation): void {
563
+ let tokenExpectations = this.expectations.get(token);
564
+ if (!tokenExpectations) {
565
+ tokenExpectations = new Map();
566
+ this.expectations.set(token, tokenExpectations);
567
+ }
568
+
569
+ let methodExpectations = tokenExpectations.get(method);
570
+ if (!methodExpectations) {
571
+ methodExpectations = [];
572
+ tokenExpectations.set(method, methodExpectations);
573
+ }
574
+
575
+ methodExpectations.push(expectation);
576
+ }
577
+
578
+ /**
579
+ * Get expectations for a token and method
580
+ */
581
+ private getExpectations(token: InjectionToken<any>, method: string): SpyExpectation[] {
582
+ const tokenExpectations = this.expectations.get(token);
583
+ if (!tokenExpectations) {
584
+ return [];
585
+ }
586
+
587
+ return tokenExpectations.get(method) || [];
588
+ }
589
+
590
+ /**
591
+ * Clear all expectations
592
+ */
593
+ clearExpectations(token?: InjectionToken<any>): void {
594
+ if (token) {
595
+ this.expectations.delete(token);
596
+ } else {
597
+ this.expectations.clear();
598
+ }
599
+ }
600
+
601
+ /**
602
+ * Verify no unexpected calls
603
+ */
604
+ verifyNoUnexpectedCalls(): void {
605
+ const violations: string[] = [];
606
+
607
+ for (const [token, spyMap] of this.spies) {
608
+ for (const [method, spy] of spyMap) {
609
+ const calls = spy.mock.calls;
610
+ const expectations = this.getExpectations(token, method as string);
611
+
612
+ // If there are calls but no expectations set, they are unexpected
613
+ if (calls.length > 0 && expectations.length === 0) {
614
+ const tokenName = typeof token === 'string' ? token : String(token);
615
+ violations.push(
616
+ `Unexpected ${calls.length} call(s) to ${tokenName}.${method as string}. ` +
617
+ `Expected no calls but got: ${JSON.stringify(calls)}`
618
+ );
619
+ }
620
+
621
+ // Verify each expectation
622
+ for (const expectation of expectations) {
623
+ if (!expectation.verify(spy)) {
624
+ const tokenName = typeof token === 'string' ? token : String(token);
625
+ violations.push(`Expectation failed for ${tokenName}.${method as string}: ${expectation.getMessage()}`);
626
+ }
627
+ }
628
+ }
629
+ }
630
+
631
+ if (violations.length > 0) {
632
+ throw new Error(`Unexpected calls detected:\n${violations.join('\n')}`);
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Override register to track registered tokens for leak detection
638
+ */
639
+ override register<T>(
640
+ tokenOrProvider: InjectionToken<T> | Provider<T> | Constructor<T>,
641
+ providerOrOptions?: ProviderDefinition<T> | RegistrationOptions,
642
+ optionsArg?: RegistrationOptions
643
+ ): this {
644
+ // Track registered tokens for leak detection and memory tracking
645
+ if (this.detectLeaks || this.trackMemory) {
646
+ // Extract token from various formats
647
+ let token: InjectionToken<T> | undefined;
648
+ if (
649
+ typeof tokenOrProvider === 'function' ||
650
+ typeof tokenOrProvider === 'string' ||
651
+ typeof tokenOrProvider === 'symbol'
652
+ ) {
653
+ token = tokenOrProvider as InjectionToken<T>;
654
+ } else if (tokenOrProvider && typeof tokenOrProvider === 'object' && 'id' in tokenOrProvider) {
655
+ token = tokenOrProvider as InjectionToken<T>;
656
+ }
657
+
658
+ if (token) {
659
+ this.registeredTokens.add(token);
660
+ }
661
+ }
662
+
663
+ return super.register(tokenOrProvider as any, providerOrOptions as any, optionsArg);
664
+ }
665
+
666
+ /**
667
+ * Override resolve to handle auto-mocking and leak detection
668
+ */
669
+ override resolve<T>(token: InjectionToken<T>): T {
670
+ try {
671
+ // Track resolved tokens for leak detection
672
+ if (this.detectLeaks) {
673
+ this.resolvedTokens.add(token);
674
+ }
675
+
676
+ // Try to resolve from this container first (for overrides)
677
+ const result = super.resolve(token);
678
+ return result;
679
+ } catch (error) {
680
+ // If not found and we have an original container, try that
681
+ if (this.originalContainer) {
682
+ try {
683
+ const result = this.originalContainer.resolve(token);
684
+ if (this.detectLeaks) {
685
+ this.resolvedTokens.add(token);
686
+ }
687
+ return result;
688
+ } catch (_originalError) {
689
+ // Continue to auto-mock if enabled
690
+ }
691
+ }
692
+
693
+ // Auto-mock if enabled
694
+ if (this.autoMock) {
695
+ const mock = this.createAutoMock<T>(token);
696
+ this.register(token, { useValue: mock });
697
+ return mock;
698
+ }
699
+
700
+ throw error;
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Create automatic mock
706
+ */
707
+ private createAutoMock<T>(token: InjectionToken<any>): T {
708
+ const _name =
709
+ typeof token === 'string'
710
+ ? token
711
+ : typeof token === 'symbol'
712
+ ? String(token)
713
+ : (token as any).constructor?.name || 'Unknown';
714
+
715
+ // Create a proxy that records all property access and method calls
716
+ return new Proxy({} as any, {
717
+ get: (target, prop) => {
718
+ if (typeof prop === 'string') {
719
+ // Return a mock function for methods
720
+ return vi.fn().mockImplementation((...args: any[]) => {
721
+ this.recordInteraction(token, {
722
+ method: prop,
723
+ args,
724
+ result: undefined,
725
+ timestamp: Date.now(),
726
+ });
727
+ });
728
+ }
729
+ return undefined;
730
+ },
731
+ });
732
+ }
733
+
734
+ /**
735
+ * Create test container from existing container
736
+ */
737
+ static from(container: Container): TestContainer {
738
+ const testContainer = new TestContainer();
739
+ testContainer.originalContainer = container;
740
+
741
+ // Don't copy registrations - let resolve method handle fallback
742
+ return testContainer;
743
+ }
744
+
745
+ /**
746
+ * Get current object count
747
+ */
748
+ private getObjectCount(): number {
749
+ let objectCount = 0;
750
+
751
+ // Count instances in the container
752
+ if ('instances' in this) {
753
+ objectCount += (this as any).instances.size;
754
+ }
755
+
756
+ // Count mocks
757
+ objectCount += this.mocks.size;
758
+
759
+ // Count all registered tokens (including provider objects)
760
+ objectCount += this.registeredTokens.size;
761
+
762
+ return objectCount;
763
+ }
764
+
765
+ /**
766
+ * Get memory usage
767
+ */
768
+ getMemoryUsage(): { heapUsed: number; heapTotal: number; objectCount: number } {
769
+ if (!this.trackMemory) {
770
+ return { heapUsed: 0, heapTotal: 0, objectCount: 0 };
771
+ }
772
+
773
+ const memUsage = process.memoryUsage();
774
+ const currentObjectCount = this.getObjectCount();
775
+
776
+ return {
777
+ heapUsed: memUsage.heapUsed,
778
+ heapTotal: memUsage.heapTotal,
779
+ objectCount: currentObjectCount,
780
+ };
781
+ }
782
+
783
+ /**
784
+ * Stub with partial mocking and proper method creation
785
+ */
786
+ partialStub<T>(token: InjectionToken<T>, stubs: Partial<T>): this {
787
+ const stubObject = {} as any;
788
+
789
+ for (const key in stubs) {
790
+ const value = stubs[key];
791
+ if (typeof value === 'function') {
792
+ stubObject[key] = value;
793
+ } else {
794
+ // Create a function that returns the stubbed value
795
+ stubObject[key] = vi.fn().mockReturnValue(value);
796
+ }
797
+ }
798
+
799
+ this.register(token, { useValue: stubObject }, { override: true, tags: ['override'] });
800
+ return this;
801
+ }
802
+
803
+ /**
804
+ * Get leaked tokens (tokens that were registered but not resolved)
805
+ */
806
+ getLeakedTokens(): InjectionToken<any>[] {
807
+ if (!this.detectLeaks) {
808
+ return [];
809
+ }
810
+
811
+ const leaked: InjectionToken<any>[] = [];
812
+
813
+ // Check registrations that were never resolved
814
+ for (const token of this.registeredTokens) {
815
+ if (!this.resolvedTokens.has(token)) {
816
+ leaked.push(token);
817
+ }
818
+ }
819
+
820
+ return leaked;
821
+ }
822
+
823
+ /**
824
+ * Get test metadata for testing
825
+ */
826
+ getTestMetadata(): {
827
+ registeredTokens: Set<InjectionToken<any>>;
828
+ resolvedTokens: Set<InjectionToken<any>>;
829
+ mocks: Map<InjectionToken<any>, any>;
830
+ spies: Map<InjectionToken<any>, Map<string, any>>;
831
+ } {
832
+ return {
833
+ registeredTokens: new Set(this.registeredTokens),
834
+ resolvedTokens: new Set(this.resolvedTokens),
835
+ mocks: new Map(this.mocks),
836
+ spies: new Map(this.spies),
837
+ };
838
+ }
839
+ }
840
+
841
+ /**
842
+ * Create a test container
843
+ */
844
+ export function createTestContainer(moduleOrOptions?: IModule | TestContainerOptions): TestContainer {
845
+ if (moduleOrOptions && 'name' in moduleOrOptions) {
846
+ // It's a module
847
+ return new TestContainer({
848
+ modules: [moduleOrOptions],
849
+ });
850
+ }
851
+
852
+ return new TestContainer(moduleOrOptions);
853
+ }
854
+
855
+ /**
856
+ * Create an isolated test container
857
+ */
858
+ export function createIsolatedTestContainer(options: TestContainerOptions = {}): TestContainer {
859
+ return new TestContainer({
860
+ ...options,
861
+ isolate: true,
862
+ });
863
+ }
864
+
865
+ /**
866
+ * Test module builder for dynamic test modules
867
+ */
868
+ export class TestModuleBuilder {
869
+ private providers: Array<[InjectionToken<any>, ProviderDefinition<any>]> = [];
870
+ private imports: IModule[] = [];
871
+ private mocks: MockConfig[] = [];
872
+
873
+ withProvider<T>(token: InjectionToken<T>, provider: ProviderDefinition<T>): this {
874
+ this.providers.push([token, provider]);
875
+ return this;
876
+ }
877
+
878
+ withMock<T>(token: InjectionToken<T>, mock: Partial<T> | T): this {
879
+ this.mocks.push({ token, mock });
880
+ return this;
881
+ }
882
+
883
+ withModule(module: IModule): this {
884
+ this.imports.push(module);
885
+ return this;
886
+ }
887
+
888
+ build(): TestContainer {
889
+ return new TestContainer({
890
+ modules: this.imports,
891
+ providers: this.providers,
892
+ mocks: this.mocks,
893
+ });
894
+ }
895
+ }