forked from jestjs/jest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
714 lines (635 loc) · 18.9 KB
/
index.js
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
/**
* Copyright (c) 2014-present, Facebook, Inc. 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.
*
* @flow
*/
import type {Global} from 'types/Global';
type Mock = any;
export type MockFunctionMetadata = {
ref?: any,
members?: {[key: string]: MockFunctionMetadata},
mockImpl?: () => any,
name?: string,
refID?: string | number,
type?: string,
value?: any,
length?: number,
};
type MockFunctionState = {
instances: Array<any>,
calls: Array<Array<any>>,
timestamps: Array<number>,
};
type MockFunctionConfig = {
isReturnValueLastSet: boolean,
defaultReturnValue: any,
mockImpl: any,
mockName: string,
specificReturnValues: Array<any>,
specificMockImpls: Array<any>,
};
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 = Object.assign(Object.create(null), {
arguments: true,
await: true,
break: true,
case: true,
catch: true,
class: true,
const: true,
continue: true,
debugger: true,
default: true,
delete: true,
do: true,
else: true,
enum: true,
eval: true,
export: true,
extends: true,
false: true,
finally: true,
for: true,
function: true,
if: true,
implements: true,
import: true,
in: true,
instanceof: true,
interface: true,
let: true,
new: true,
null: true,
package: true,
private: true,
protected: true,
public: true,
return: true,
static: true,
super: true,
switch: true,
this: true,
throw: true,
true: true,
try: true,
typeof: true,
var: true,
void: true,
while: true,
with: true,
yield: true,
});
function matchArity(fn: any, length: number): any {
let mockConstructor;
switch (length) {
case 1:
mockConstructor = function(a) {
return fn.apply(this, arguments);
};
break;
case 2:
mockConstructor = function(a, b) {
return fn.apply(this, arguments);
};
break;
case 3:
mockConstructor = function(a, b, c) {
return fn.apply(this, arguments);
};
break;
case 4:
mockConstructor = function(a, b, c, d) {
return fn.apply(this, arguments);
};
break;
case 5:
mockConstructor = function(a, b, c, d, e) {
return fn.apply(this, arguments);
};
break;
case 6:
mockConstructor = function(a, b, c, d, e, f) {
return fn.apply(this, arguments);
};
break;
case 7:
mockConstructor = function(a, b, c, d, e, f, g) {
return fn.apply(this, arguments);
};
break;
case 8:
mockConstructor = function(a, b, c, d, e, f, g, h) {
return fn.apply(this, arguments);
};
break;
case 9:
mockConstructor = function(a, b, c, d, e, f, g, h, i) {
return fn.apply(this, arguments);
};
break;
default:
mockConstructor = function() {
return fn.apply(this, arguments);
};
break;
}
return mockConstructor;
}
function isA(typeName: string, value: any): boolean {
return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
}
function getType(ref?: any): string | null {
if (isA('Function', ref) || isA('AsyncFunction', ref)) {
return 'function';
} else if (Array.isArray(ref)) {
return 'array';
} else if (isA('Object', ref)) {
return 'object';
} else if (
isA('Number', ref) ||
isA('String', ref) ||
isA('Boolean', ref) ||
isA('Symbol', ref)
) {
return 'constant';
} else if (isA('Map', ref) || isA('WeakMap', ref) || isA('Set', ref)) {
return 'collection';
} else if (isA('RegExp', ref)) {
return 'regexp';
} else if (ref === undefined) {
return 'undefined';
} else if (ref === null) {
return 'null';
} else {
return null;
}
}
function isReadonlyProp(object: any, prop: string): boolean {
return (
((prop === 'arguments' ||
prop === 'caller' ||
prop === 'callee' ||
prop === 'name' ||
prop === 'length') &&
(isA('Function', object) || isA('AsyncFunction', object))) ||
((prop === 'source' ||
prop === 'global' ||
prop === 'ignoreCase' ||
prop === 'multiline') &&
isA('RegExp', object))
);
}
function getSlots(object?: Object): Array<string> {
const slots = {};
if (!object) {
return [];
}
let parent = Object.getPrototypeOf(object);
do {
if (object === Object.getPrototypeOf(Function)) {
break;
}
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.get || object.__esModule) {
slots[prop] = true;
}
}
}
object = parent;
} while (object && (parent = Object.getPrototypeOf(object)) !== null);
return Object.keys(slots);
}
class ModuleMockerClass {
_environmentGlobal: Global;
_mockState: WeakMap<Function, MockFunctionState>;
_mockConfigRegistry: WeakMap<Function, MockFunctionConfig>;
_spyState: Set<() => void>;
ModuleMocker: Class<ModuleMockerClass>;
/**
* @see README.md
* @param global Global object of the test environment, used to create
* mocks
*/
constructor(global: Global) {
this._environmentGlobal = global;
this._mockState = new WeakMap();
this._mockConfigRegistry = new WeakMap();
this._spyState = new Set();
this.ModuleMocker = ModuleMockerClass;
}
_ensureMockConfig(f: Mock): MockFunctionConfig {
let config = this._mockConfigRegistry.get(f);
if (!config) {
config = this._defaultMockConfig();
this._mockConfigRegistry.set(f, config);
}
return config;
}
_ensureMockState(f: Mock): MockFunctionState {
let state = this._mockState.get(f);
if (!state) {
state = this._defaultMockState();
this._mockState.set(f, state);
}
return state;
}
_defaultMockConfig(): MockFunctionConfig {
return {
defaultReturnValue: undefined,
isReturnValueLastSet: false,
mockImpl: undefined,
mockName: 'jest.fn()',
specificMockImpls: [],
specificReturnValues: [],
};
}
_defaultMockState(): MockFunctionState {
return {
calls: [],
instances: [],
timestamps: [],
};
}
_makeComponent(metadata: MockFunctionMetadata, restore?: () => void): Mock {
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') {
/* eslint-disable prefer-const */
let f;
/* eslint-enable prefer-const */
const prototype =
(metadata.members &&
metadata.members.prototype &&
metadata.members.prototype.members) ||
{};
const prototypeSlots = getSlots(prototype);
const mocker = this;
const mockConstructor = matchArity(function() {
const mockState = mocker._ensureMockState(f);
const mockConfig = mocker._ensureMockConfig(f);
mockState.instances.push(this);
mockState.calls.push(Array.prototype.slice.call(arguments));
mockState.timestamps.push(Date.now());
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') {
const protoImpl = this[slot];
this[slot] = mocker.generateFromMetadata(prototype[slot]);
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);
}
const returnValue = mockConfig.defaultReturnValue;
// If return value is last set, either specific or default, i.e.
// mockReturnValueOnce()/mockReturnValue() is called and no
// mockImplementationOnce()/mockImplementation() is called after that.
// use the set return value.
if (mockConfig.specificReturnValues.length) {
return mockConfig.specificReturnValues.shift();
}
if (mockConfig.isReturnValueLastSet) {
return mockConfig.defaultReturnValue;
}
// If mockImplementationOnce()/mockImplementation() is last set,
// or specific return values are used up, use the mock implementation.
let specificMockImpl;
if (returnValue === undefined) {
specificMockImpl = mockConfig.specificMockImpls.shift();
if (specificMockImpl === undefined) {
specificMockImpl = mockConfig.mockImpl;
}
if (specificMockImpl) {
return specificMockImpl.apply(this, arguments);
}
}
// Otherwise use prototype implementation
if (returnValue === undefined && f._protoImpl) {
return f._protoImpl.apply(this, arguments);
}
return returnValue;
}, metadata.length || 0);
f = this._createMockFunction(metadata, mockConstructor);
f._isMockFunction = true;
f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl;
if (typeof restore === 'function') {
this._spyState.add(restore);
}
this._mockState.set(f, this._defaultMockState());
this._mockConfigRegistry.set(f, this._defaultMockConfig());
// $FlowFixMe - defineProperty getters not supported
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 = () => {
this._mockState.delete(f);
this._mockConfigRegistry.delete(f);
return f;
};
f.mockReturnValueOnce = value => {
// next function call will return this value or default return value
const mockConfig = this._ensureMockConfig(f);
mockConfig.specificReturnValues.push(value);
return f;
};
f.mockReturnValue = value => {
// next function call will return specified return value or this one
const mockConfig = this._ensureMockConfig(f);
mockConfig.isReturnValueLastSet = true;
mockConfig.defaultReturnValue = value;
return f;
};
f.mockImplementationOnce = fn => {
// next function call will use this mock implementation return value
// or default mock implementation return value
const mockConfig = this._ensureMockConfig(f);
mockConfig.isReturnValueLastSet = false;
mockConfig.specificMockImpls.push(fn);
return f;
};
f.mockImplementation = fn => {
// next function call will use mock implementation return value
const mockConfig = this._ensureMockConfig(f);
mockConfig.isReturnValueLastSet = false;
mockConfig.defaultReturnValue = undefined;
mockConfig.mockImpl = fn;
return f;
};
f.mockReturnThis = () =>
f.mockImplementation(function() {
return this;
});
f.mockName = name => {
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);
}
f.mockRestore = restore ? restore : () => {};
return f;
} else {
const unknownType = metadata.type || 'undefined type';
throw new Error('Unrecognized type ' + unknownType);
}
}
_createMockFunction(
metadata: MockFunctionMetadata,
mockConstructor: () => any,
): any {
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;
}
// It's a syntax error to define functions with a reserved keyword
// as name.
if (RESERVED_KEYWORDS[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);
}
_generateMock(
metadata: MockFunctionMetadata,
callbacks: Array<() => any>,
refs: Object,
): Mock {
const mock = this._makeComponent(metadata);
if (metadata.refID != null) {
refs[metadata.refID] = mock;
}
getSlots(metadata.members).forEach(slot => {
const slotMetadata = (metadata.members && metadata.members[slot]) || {};
if (slotMetadata.ref != null) {
callbacks.push(() => (mock[slot] = refs[slotMetadata.ref]));
} else {
mock[slot] = this._generateMock(slotMetadata, callbacks, refs);
}
});
if (
metadata.type !== 'undefined' &&
metadata.type !== 'null' &&
mock.prototype
) {
mock.prototype.constructor = mock;
}
return mock;
}
/**
* @see README.md
* @param metadata Metadata for the mock in the schema returned by the
* getMetadata method of this module.
*/
generateFromMetadata(_metadata: MockFunctionMetadata): Mock {
const callbacks = [];
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(component: any, _refs?: Map<any, any>): ?MockFunctionMetadata {
const refs = _refs || new Map();
const ref = refs.get(component);
if (ref != null) {
return {ref};
}
const type = getType(component);
if (!type) {
return null;
}
const metadata: MockFunctionMetadata = {type};
if (
type === 'constant' ||
type === 'collection' ||
type === 'undefined' ||
type === 'null'
) {
metadata.value = component;
return metadata;
} else if (type === 'function') {
metadata.name = component.name;
if (component._isMockFunction) {
metadata.mockImpl = component.getMockImplementation();
}
}
metadata.refID = refs.size;
refs.set(component, metadata.refID);
let members = null;
// Leave arrays alone
if (type !== 'array') {
if (type !== 'undefined') {
getSlots(component).forEach(slot => {
if (
type === 'function' &&
component._isMockFunction &&
slot.match(/^mock/)
) {
return;
}
if (
(!component.hasOwnProperty && component[slot] !== undefined) ||
(component.hasOwnProperty && component.hasOwnProperty(slot)) ||
(type === 'object' && component[slot] != Object.prototype[slot])
) {
const slotMetadata = this.getMetadata(component[slot], refs);
if (slotMetadata) {
if (!members) {
members = {};
}
members[slot] = slotMetadata;
}
}
});
}
// If component is native code function, prototype might be undefined
if (type === 'function' && component.prototype) {
const prototype = this.getMetadata(component.prototype, refs);
if (prototype && prototype.members) {
if (!members) {
members = {};
}
members.prototype = prototype;
}
}
}
if (members) {
metadata.members = members;
}
return metadata;
}
isMockFunction(fn: any): boolean {
return !!(fn && fn._isMockFunction);
}
fn(implementation?: any): any {
const length = implementation ? implementation.length : 0;
const fn = this._makeComponent({length, type: 'function'});
if (implementation) {
fn.mockImplementation(implementation);
}
return fn;
}
spyOn(object: any, methodName: any): any {
if (typeof object !== 'object' && typeof object !== 'function') {
throw new Error(
'Cannot spyOn on a primitive value; ' + this._typeOf(object) + ' given',
);
}
const original = object[methodName];
if (!this.isMockFunction(original)) {
if (typeof original !== 'function') {
throw new Error(
'Cannot spy the ' +
methodName +
' property because it is not a function; ' +
this._typeOf(original) +
' given instead',
);
}
object[methodName] = this._makeComponent({type: 'function'}, () => {
object[methodName] = original;
});
object[methodName].mockImplementation(function() {
return original.apply(this, arguments);
});
}
return object[methodName];
}
clearAllMocks() {
this._mockState = new WeakMap();
}
resetAllMocks() {
this._mockConfigRegistry = new WeakMap();
this._mockState = new WeakMap();
}
restoreAllMocks() {
this._spyState.forEach(restore => restore());
this._spyState = new Set();
}
_typeOf(value: any): string {
return value == null ? '' + value : typeof value;
}
}
export type ModuleMocker = ModuleMockerClass;
module.exports = new ModuleMockerClass(global);