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