-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
index.ts
1204 lines (1076 loc) · 33.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable local/ban-types-eventually, local/prefer-rest-params-eventually */
export type MockFunctionMetadataType =
| 'object'
| 'array'
| 'regexp'
| 'function'
| 'constant'
| 'collection'
| 'null'
| 'undefined';
export type MockFunctionMetadata<
T,
Y extends Array<unknown>,
Type = MockFunctionMetadataType,
> = {
ref?: number;
members?: Record<string, MockFunctionMetadata<T, Y>>;
mockImpl?: (...args: Y) => T;
name?: string;
refID?: number;
type?: Type;
value?: T;
length?: number;
};
export type MockableFunction = (...args: Array<any>) => any;
export type MethodKeysOf<T> = {
[K in keyof T]: T[K] extends MockableFunction ? K : never;
}[keyof T];
export type PropertyKeysOf<T> = {
[K in keyof T]: T[K] extends MockableFunction ? never : K;
}[keyof T];
export type ArgumentsOf<T> = T extends (...args: infer A) => any ? A : never;
export type ConstructorArgumentsOf<T> = T extends new (...args: infer A) => any
? A
: never;
export type MaybeMockedConstructor<T> = T extends new (
...args: Array<any>
) => infer R
? MockInstance<R, ConstructorArgumentsOf<T>>
: T;
export type MockedFunction<T extends MockableFunction> = MockWithArgs<T> & {
[K in keyof T]: T[K];
};
export type MockedFunctionDeep<T extends MockableFunction> = MockWithArgs<T> &
MockedObjectDeep<T>;
export type MockedObject<T> = MaybeMockedConstructor<T> & {
[K in MethodKeysOf<T>]: T[K] extends MockableFunction
? MockedFunction<T[K]>
: T[K];
} & {[K in PropertyKeysOf<T>]: T[K]};
export type MockedObjectDeep<T> = MaybeMockedConstructor<T> & {
[K in MethodKeysOf<T>]: T[K] extends MockableFunction
? MockedFunctionDeep<T[K]>
: T[K];
} & {[K in PropertyKeysOf<T>]: MaybeMockedDeep<T[K]>};
export type MaybeMockedDeep<T> = T extends MockableFunction
? MockedFunctionDeep<T>
: T extends object
? MockedObjectDeep<T>
: T;
export type MaybeMocked<T> = T extends MockableFunction
? MockedFunction<T>
: T extends object
? MockedObject<T>
: T;
export type ArgsType<T> = T extends (...args: infer A) => any ? A : never;
export type Mocked<T> = {
[P in keyof T]: T[P] extends (...args: Array<any>) => any
? MockInstance<ReturnType<T[P]>, ArgsType<T[P]>>
: T[P] extends Constructable
? MockedClass<T[P]>
: T[P];
} & T;
export type MockedClass<T extends Constructable> = MockInstance<
InstanceType<T>,
T extends new (...args: infer P) => any ? P : never
> & {
prototype: T extends {prototype: any} ? Mocked<T['prototype']> : never;
} & T;
export interface Constructable {
new (...args: Array<any>): any;
}
export interface MockWithArgs<T extends MockableFunction>
extends MockInstance<ReturnType<T>, ArgumentsOf<T>> {
new (...args: ConstructorArgumentsOf<T>): T;
(...args: ArgumentsOf<T>): ReturnType<T>;
}
export interface Mock<T, Y extends Array<unknown> = Array<unknown>>
extends Function,
MockInstance<T, Y> {
new (...args: Y): T;
(...args: Y): T;
}
export interface SpyInstance<T, Y extends Array<unknown>>
extends MockInstance<T, Y> {}
export interface MockInstance<T, Y extends Array<unknown>> {
_isMockFunction: true;
_protoImpl: Function;
getMockName(): string;
getMockImplementation(): Function | undefined;
mock: MockFunctionState<T, Y>;
mockClear(): this;
mockReset(): this;
mockRestore(): void;
mockImplementation(fn: (...args: Y) => T): this;
mockImplementation(fn: () => Promise<T>): this;
mockImplementationOnce(fn: (...args: Y) => T): this;
mockImplementationOnce(fn: () => Promise<T>): this;
mockName(name: string): this;
mockReturnThis(): this;
mockReturnValue(value: T): this;
mockReturnValueOnce(value: T): this;
mockResolvedValue(value: Unpromisify<T>): this;
mockResolvedValueOnce(value: Unpromisify<T>): this;
mockRejectedValue(value: unknown): this;
mockRejectedValueOnce(value: unknown): this;
}
type Unpromisify<T> = T extends Promise<infer R> ? R : never;
/**
* Possible types of a MockFunctionResult.
* 'return': The call completed by returning normally.
* 'throw': The call completed by throwing a value.
* 'incomplete': The call has not completed yet. This is possible if you read
* the mock function result from within the mock function itself
* (or a function called by the mock function).
*/
type MockFunctionResultType = 'return' | 'throw' | 'incomplete';
/**
* Represents the result of a single call to a mock function.
*/
type MockFunctionResult = {
/**
* Indicates how the call completed.
*/
type: MockFunctionResultType;
/**
* The value that was either thrown or returned by the function.
* Undefined when type === 'incomplete'.
*/
value: unknown;
};
type MockFunctionState<T, Y extends Array<unknown>> = {
calls: Array<Y>;
instances: Array<T>;
invocationCallOrder: Array<number>;
/**
* Getter for retrieving the last call arguments
*/
lastCall?: Y;
/**
* List of results of calls to the mock function.
*/
results: Array<MockFunctionResult>;
};
type MockFunctionConfig = {
mockImpl: Function | undefined;
mockName: string;
specificReturnValues: Array<unknown>;
specificMockImpls: Array<Function>;
};
// see https://github.com/Microsoft/TypeScript/issues/25215
type NonFunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends (...args: Array<any>) => any ? never : K;
}[keyof T] &
string;
type FunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends (...args: Array<any>) => any ? K : never;
}[keyof T] &
string;
const MOCK_CONSTRUCTOR_NAME = 'mockConstructor';
const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-\/:-@\[-`{-~]/;
const FUNCTION_NAME_RESERVED_REPLACE = new RegExp(
FUNCTION_NAME_RESERVED_PATTERN.source,
'g',
);
const RESERVED_KEYWORDS = new Set([
'arguments',
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'enum',
'eval',
'export',
'extends',
'false',
'finally',
'for',
'function',
'if',
'implements',
'import',
'in',
'instanceof',
'interface',
'let',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'static',
'super',
'switch',
'this',
'throw',
'true',
'try',
'typeof',
'var',
'void',
'while',
'with',
'yield',
]);
function matchArity(fn: Function, length: number): Function {
let mockConstructor;
switch (length) {
case 1:
mockConstructor = function (this: unknown, _a: unknown) {
return fn.apply(this, arguments);
};
break;
case 2:
mockConstructor = function (this: unknown, _a: unknown, _b: unknown) {
return fn.apply(this, arguments);
};
break;
case 3:
mockConstructor = function (
this: unknown,
_a: unknown,
_b: unknown,
_c: unknown,
) {
return fn.apply(this, arguments);
};
break;
case 4:
mockConstructor = function (
this: unknown,
_a: unknown,
_b: unknown,
_c: unknown,
_d: unknown,
) {
return fn.apply(this, arguments);
};
break;
case 5:
mockConstructor = function (
this: unknown,
_a: unknown,
_b: unknown,
_c: unknown,
_d: unknown,
_e: unknown,
) {
return fn.apply(this, arguments);
};
break;
case 6:
mockConstructor = function (
this: unknown,
_a: unknown,
_b: unknown,
_c: unknown,
_d: unknown,
_e: unknown,
_f: unknown,
) {
return fn.apply(this, arguments);
};
break;
case 7:
mockConstructor = function (
this: unknown,
_a: unknown,
_b: unknown,
_c: unknown,
_d: unknown,
_e: unknown,
_f: unknown,
_g: unknown,
) {
return fn.apply(this, arguments);
};
break;
case 8:
mockConstructor = function (
this: unknown,
_a: unknown,
_b: unknown,
_c: unknown,
_d: unknown,
_e: unknown,
_f: unknown,
_g: unknown,
_h: unknown,
) {
return fn.apply(this, arguments);
};
break;
case 9:
mockConstructor = function (
this: unknown,
_a: unknown,
_b: unknown,
_c: unknown,
_d: unknown,
_e: unknown,
_f: unknown,
_g: unknown,
_h: unknown,
_i: unknown,
) {
return fn.apply(this, arguments);
};
break;
default:
mockConstructor = function (this: unknown) {
return fn.apply(this, arguments);
};
break;
}
return mockConstructor;
}
function getObjectType(value: unknown): string {
return Object.prototype.toString.apply(value).slice(8, -1);
}
function getType(ref?: unknown): MockFunctionMetadataType | null {
const typeName = getObjectType(ref);
if (
typeName === 'Function' ||
typeName === 'AsyncFunction' ||
typeName === 'GeneratorFunction'
) {
return 'function';
} else if (Array.isArray(ref)) {
return 'array';
} else if (typeName === 'Object') {
return 'object';
} else if (
typeName === 'Number' ||
typeName === 'String' ||
typeName === 'Boolean' ||
typeName === 'Symbol'
) {
return 'constant';
} else if (
typeName === 'Map' ||
typeName === 'WeakMap' ||
typeName === 'Set'
) {
return 'collection';
} else if (typeName === 'RegExp') {
return 'regexp';
} else if (ref === undefined) {
return 'undefined';
} else if (ref === null) {
return 'null';
} else {
return null;
}
}
function isReadonlyProp(object: any, prop: string): boolean {
if (
prop === 'arguments' ||
prop === 'caller' ||
prop === 'callee' ||
prop === 'name' ||
prop === 'length'
) {
const typeName = getObjectType(object);
return (
typeName === 'Function' ||
typeName === 'AsyncFunction' ||
typeName === 'GeneratorFunction'
);
}
if (
prop === 'source' ||
prop === 'global' ||
prop === 'ignoreCase' ||
prop === 'multiline'
) {
return getObjectType(object) === 'RegExp';
}
return false;
}
export class ModuleMocker {
private _environmentGlobal: typeof globalThis;
private _mockState: WeakMap<Mock<any, any>, MockFunctionState<any, any>>;
private _mockConfigRegistry: WeakMap<Function, MockFunctionConfig>;
private _spyState: Set<() => void>;
private _invocationCallCounter: number;
/**
* @see README.md
* @param global Global object of the test environment, used to create
* mocks
*/
constructor(global: typeof globalThis) {
this._environmentGlobal = global;
this._mockState = new WeakMap();
this._mockConfigRegistry = new WeakMap();
this._spyState = new Set();
this._invocationCallCounter = 1;
}
private _getSlots(object?: Record<string, any>): Array<string> {
if (!object) {
return [];
}
const slots = new Set<string>();
const EnvObjectProto = this._environmentGlobal.Object.prototype;
const EnvFunctionProto = this._environmentGlobal.Function.prototype;
const EnvRegExpProto = this._environmentGlobal.RegExp.prototype;
// Also check the builtins in the current context as they leak through
// core node modules.
const ObjectProto = Object.prototype;
const FunctionProto = Function.prototype;
const RegExpProto = RegExp.prototype;
// Properties of Object.prototype, Function.prototype and RegExp.prototype
// are never reported as slots
while (
object != null &&
object !== EnvObjectProto &&
object !== EnvFunctionProto &&
object !== EnvRegExpProto &&
object !== ObjectProto &&
object !== FunctionProto &&
object !== RegExpProto
) {
const ownNames = Object.getOwnPropertyNames(object);
for (let i = 0; i < ownNames.length; i++) {
const prop = ownNames[i];
if (!isReadonlyProp(object, prop)) {
const propDesc = Object.getOwnPropertyDescriptor(object, prop);
if ((propDesc !== undefined && !propDesc.get) || object.__esModule) {
slots.add(prop);
}
}
}
object = Object.getPrototypeOf(object);
}
return Array.from(slots);
}
private _ensureMockConfig<T, Y extends Array<unknown>>(
f: Mock<T, Y>,
): MockFunctionConfig {
let config = this._mockConfigRegistry.get(f);
if (!config) {
config = this._defaultMockConfig();
this._mockConfigRegistry.set(f, config);
}
return config;
}
private _ensureMockState<T, Y extends Array<unknown>>(
f: Mock<T, Y>,
): MockFunctionState<T, Y> {
let state = this._mockState.get(f);
if (!state) {
state = this._defaultMockState();
this._mockState.set(f, state);
}
if (state.calls.length > 0) {
state.lastCall = state.calls[state.calls.length - 1];
}
return state;
}
private _defaultMockConfig(): MockFunctionConfig {
return {
mockImpl: undefined,
mockName: 'jest.fn()',
specificMockImpls: [],
specificReturnValues: [],
};
}
private _defaultMockState<T, Y extends Array<unknown>>(): MockFunctionState<
T,
Y
> {
return {
calls: [],
instances: [],
invocationCallOrder: [],
results: [],
};
}
private _makeComponent<T, Y extends Array<unknown>>(
metadata: MockFunctionMetadata<T, Y, 'object'>,
restore?: () => void,
): Record<string, any>;
private _makeComponent<T, Y extends Array<unknown>>(
metadata: MockFunctionMetadata<T, Y, 'array'>,
restore?: () => void,
): Array<unknown>;
private _makeComponent<T, Y extends Array<unknown>>(
metadata: MockFunctionMetadata<T, Y, 'regexp'>,
restore?: () => void,
): RegExp;
private _makeComponent<T, Y extends Array<unknown>>(
metadata: MockFunctionMetadata<
T,
Y,
'constant' | 'collection' | 'null' | 'undefined'
>,
restore?: () => void,
): T;
private _makeComponent<T, Y extends Array<unknown>>(
metadata: MockFunctionMetadata<T, Y, 'function'>,
restore?: () => void,
): Mock<T, Y>;
private _makeComponent<T, Y extends Array<unknown>>(
metadata: MockFunctionMetadata<T, Y>,
restore?: () => void,
):
| Record<string, any>
| Array<unknown>
| RegExp
| T
| undefined
| Mock<T, Y> {
if (metadata.type === 'object') {
return new this._environmentGlobal.Object();
} else if (metadata.type === 'array') {
return new this._environmentGlobal.Array();
} else if (metadata.type === 'regexp') {
return new this._environmentGlobal.RegExp('');
} else if (
metadata.type === 'constant' ||
metadata.type === 'collection' ||
metadata.type === 'null' ||
metadata.type === 'undefined'
) {
return metadata.value;
} else if (metadata.type === 'function') {
const prototype =
(metadata.members &&
metadata.members.prototype &&
metadata.members.prototype.members) ||
{};
const prototypeSlots = this._getSlots(prototype);
const mocker = this;
const mockConstructor = matchArity(function (this: T, ...args: Y) {
const mockState = mocker._ensureMockState(f);
const mockConfig = mocker._ensureMockConfig(f);
mockState.instances.push(this);
mockState.calls.push(args);
// Create and record an "incomplete" mock result immediately upon
// calling rather than waiting for the mock to return. This avoids
// issues caused by recursion where results can be recorded in the
// wrong order.
const mockResult: MockFunctionResult = {
type: 'incomplete',
value: undefined,
};
mockState.results.push(mockResult);
mockState.invocationCallOrder.push(mocker._invocationCallCounter++);
// Will be set to the return value of the mock if an error is not thrown
let finalReturnValue;
// Will be set to the error that is thrown by the mock (if it throws)
let thrownError;
// Will be set to true if the mock throws an error. The presence of a
// value in `thrownError` is not a 100% reliable indicator because a
// function could throw a value of undefined.
let callDidThrowError = false;
try {
// The bulk of the implementation is wrapped in an immediately
// executed arrow function so the return value of the mock function
// can be easily captured and recorded, despite the many separate
// return points within the logic.
finalReturnValue = (() => {
if (this instanceof f) {
// This is probably being called as a constructor
prototypeSlots.forEach(slot => {
// Copy prototype methods to the instance to make
// it easier to interact with mock instance call and
// return values
if (prototype[slot].type === 'function') {
// @ts-expect-error no index signature
const protoImpl = this[slot];
// @ts-expect-error no index signature
this[slot] = mocker.generateFromMetadata(prototype[slot]);
// @ts-expect-error no index signature
this[slot]._protoImpl = protoImpl;
}
});
// Run the mock constructor implementation
const mockImpl = mockConfig.specificMockImpls.length
? mockConfig.specificMockImpls.shift()
: mockConfig.mockImpl;
return mockImpl && mockImpl.apply(this, arguments);
}
// If mockImplementationOnce()/mockImplementation() is last set,
// implementation use the mock
let specificMockImpl = mockConfig.specificMockImpls.shift();
if (specificMockImpl === undefined) {
specificMockImpl = mockConfig.mockImpl;
}
if (specificMockImpl) {
return specificMockImpl.apply(this, arguments);
}
// Otherwise use prototype implementation
if (f._protoImpl) {
return f._protoImpl.apply(this, arguments);
}
return undefined;
})();
} catch (error) {
// Store the thrown error so we can record it, then re-throw it.
thrownError = error;
callDidThrowError = true;
throw error;
} finally {
// Record the result of the function.
// NOTE: Intentionally NOT pushing/indexing into the array of mock
// results here to avoid corrupting results data if mockClear()
// is called during the execution of the mock.
mockResult.type = callDidThrowError ? 'throw' : 'return';
mockResult.value = callDidThrowError ? thrownError : finalReturnValue;
}
return finalReturnValue;
}, metadata.length || 0);
const f = this._createMockFunction(
metadata,
mockConstructor,
) as unknown as Mock<T, Y>;
f._isMockFunction = true;
f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl;
if (typeof restore === 'function') {
this._spyState.add(restore);
}
this._mockState.set(f, this._defaultMockState<T, Y>());
this._mockConfigRegistry.set(f, this._defaultMockConfig());
Object.defineProperty(f, 'mock', {
configurable: false,
enumerable: true,
get: () => this._ensureMockState(f),
set: val => this._mockState.set(f, val),
});
f.mockClear = () => {
this._mockState.delete(f);
return f;
};
f.mockReset = () => {
f.mockClear();
this._mockConfigRegistry.delete(f);
return f;
};
f.mockRestore = () => {
f.mockReset();
return restore ? restore() : undefined;
};
f.mockReturnValueOnce = (value: T) =>
// next function call will return this value or default return value
f.mockImplementationOnce(() => value);
f.mockResolvedValueOnce = (value: Unpromisify<T>) =>
f.mockImplementationOnce(() => Promise.resolve(value as T));
f.mockRejectedValueOnce = (value: unknown) =>
f.mockImplementationOnce(() => Promise.reject(value));
f.mockReturnValue = (value: T) =>
// next function call will return specified return value or this one
f.mockImplementation(() => value);
f.mockResolvedValue = (value: Unpromisify<T>) =>
f.mockImplementation(() => Promise.resolve(value as T));
f.mockRejectedValue = (value: unknown) =>
f.mockImplementation(() => Promise.reject(value));
f.mockImplementationOnce = (
fn: ((...args: Y) => T) | (() => Promise<T>),
): Mock<T, Y> => {
// next function call will use this mock implementation return value
// or default mock implementation return value
const mockConfig = this._ensureMockConfig(f);
mockConfig.specificMockImpls.push(fn);
return f;
};
f.mockImplementation = (
fn: ((...args: Y) => T) | (() => Promise<T>),
): Mock<T, Y> => {
// next function call will use mock implementation return value
const mockConfig = this._ensureMockConfig(f);
mockConfig.mockImpl = fn;
return f;
};
f.mockReturnThis = () =>
f.mockImplementation(function (this: T) {
return this;
});
f.mockName = (name: string) => {
if (name) {
const mockConfig = this._ensureMockConfig(f);
mockConfig.mockName = name;
}
return f;
};
f.getMockName = () => {
const mockConfig = this._ensureMockConfig(f);
return mockConfig.mockName || 'jest.fn()';
};
if (metadata.mockImpl) {
f.mockImplementation(metadata.mockImpl);
}
return f;
} else {
const unknownType = metadata.type || 'undefined type';
throw new Error('Unrecognized type ' + unknownType);
}
}
private _createMockFunction<T, Y extends Array<unknown>>(
metadata: MockFunctionMetadata<T, Y>,
mockConstructor: Function,
): Function {
let name = metadata.name;
if (!name) {
return mockConstructor;
}
// Preserve `name` property of mocked function.
const boundFunctionPrefix = 'bound ';
let bindCall = '';
// if-do-while for perf reasons. The common case is for the if to fail.
if (name && name.startsWith(boundFunctionPrefix)) {
do {
name = name.substring(boundFunctionPrefix.length);
// Call bind() just to alter the function name.
bindCall = '.bind(null)';
} while (name && name.startsWith(boundFunctionPrefix));
}
// Special case functions named `mockConstructor` to guard for infinite
// loops.
if (name === MOCK_CONSTRUCTOR_NAME) {
return mockConstructor;
}
if (
// It's a syntax error to define functions with a reserved keyword
// as name.
RESERVED_KEYWORDS.has(name) ||
// It's also a syntax error to define functions with a name that starts with a number
/^\d/.test(name)
) {
name = '$' + name;
}
// It's also a syntax error to define a function with a reserved character
// as part of it's name.
if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) {
name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$');
}
const body =
'return function ' +
name +
'() {' +
'return ' +
MOCK_CONSTRUCTOR_NAME +
'.apply(this,arguments);' +
'}' +
bindCall;
const createConstructor = new this._environmentGlobal.Function(
MOCK_CONSTRUCTOR_NAME,
body,
);
return createConstructor(mockConstructor);
}
private _generateMock<T, Y extends Array<unknown>>(
metadata: MockFunctionMetadata<T, Y>,
callbacks: Array<Function>,
refs: {
[key: string]:
| Record<string, any>
| Array<unknown>
| RegExp
| T
| undefined
| Mock<T, Y>;
},
): Mock<T, Y> {
// metadata not compatible but it's the same type, maybe problem with
// overloading of _makeComponent and not _generateMock?
// @ts-expect-error
const mock = this._makeComponent(metadata);
if (metadata.refID != null) {
refs[metadata.refID] = mock;
}
this._getSlots(metadata.members).forEach(slot => {
const slotMetadata = (metadata.members && metadata.members[slot]) || {};
if (slotMetadata.ref != null) {
callbacks.push(
(function (ref) {
return () => (mock[slot] = refs[ref]);
})(slotMetadata.ref),
);
} else {
mock[slot] = this._generateMock(slotMetadata, callbacks, refs);
}
});
if (
metadata.type !== 'undefined' &&
metadata.type !== 'null' &&
mock.prototype &&
typeof mock.prototype === 'object'
) {
mock.prototype.constructor = mock;
}
return mock as Mock<T, Y>;
}
/**
* @see README.md
* @param _metadata Metadata for the mock in the schema returned by the
* getMetadata method of this module.
*/
generateFromMetadata<T, Y extends Array<unknown>>(
_metadata: MockFunctionMetadata<T, Y>,
): Mock<T, Y> {
const callbacks: Array<Function> = [];
const refs = {};
const mock = this._generateMock(_metadata, callbacks, refs);
callbacks.forEach(setter => setter());
return mock;
}
/**
* @see README.md
* @param component The component for which to retrieve metadata.
*/
getMetadata<T, Y extends Array<unknown>>(
component: T,
_refs?: Map<T, number>,
): MockFunctionMetadata<T, Y> | null {
const refs = _refs || new Map<T, number>();
const ref = refs.get(component);
if (ref != null) {
return {ref};
}
const type = getType(component);
if (!type) {
return null;
}
const metadata: MockFunctionMetadata<T, Y> = {type};
if (
type === 'constant' ||
type === 'collection' ||
type === 'undefined' ||
type === 'null'
) {
metadata.value = component;
return metadata;
} else if (type === 'function') {
// @ts-expect-error this is a function so it has a name
metadata.name = component.name;
// @ts-expect-error may be a mock
if (component._isMockFunction === true) {
// @ts-expect-error may be a mock
metadata.mockImpl = component.getMockImplementation();
}
}
metadata.refID = refs.size;
refs.set(component, metadata.refID);
let members: {
[key: string]: MockFunctionMetadata<T, Y>;
} | null = null;
// Leave arrays alone
if (type !== 'array') {
this._getSlots(component).forEach(slot => {
if (
type === 'function' &&
// @ts-expect-error may be a mock
component._isMockFunction === true &&
slot.match(/^mock/)
) {
return;
}
// @ts-expect-error no index signature
const slotMetadata = this.getMetadata<T, Y>(component[slot], refs);
if (slotMetadata) {
if (!members) {
members = {};
}
members[slot] = slotMetadata;
}
});
}
if (members) {
metadata.members = members;
}
return metadata;
}
isMockFunction<T>(fn: unknown): fn is Mock<T> {
return !!fn && (fn as any)._isMockFunction === true;
}
fn<T, Y extends Array<unknown>>(
implementation?: (...args: Y) => T,
): Mock<T, Y> {
const length = implementation ? implementation.length : 0;
const fn = this._makeComponent<T, Y>({length, type: 'function'});
if (implementation) {