-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
index.ts
412 lines (373 loc) · 11.4 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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type {PluginObj} from '@babel/core';
import {statement} from '@babel/template';
import type {NodePath} from '@babel/traverse';
import {
type BlockStatement,
type CallExpression,
type EmptyStatement,
type Expression,
type Identifier,
type ImportDeclaration,
type MemberExpression,
type Node,
type Program,
type Super,
type VariableDeclaration,
type VariableDeclarator,
callExpression,
emptyStatement,
isIdentifier,
variableDeclaration,
} from '@babel/types';
const JEST_GLOBAL_NAME = 'jest';
const JEST_GLOBALS_MODULE_NAME = '@jest/globals';
const JEST_GLOBALS_MODULE_JEST_EXPORT_NAME = 'jest';
const hoistedVariables = new WeakSet<VariableDeclarator>();
const hoistedJestGetters = new WeakSet<CallExpression>();
const hoistedJestExpressions = new WeakSet<Expression>();
// We allow `jest`, `expect`, `require`, all default Node.js globals and all
// ES2015 built-ins to be used inside of a `jest.mock` factory.
// We also allow variables prefixed with `mock` as an escape-hatch.
const ALLOWED_IDENTIFIERS = new Set<string>(
[
'Array',
'ArrayBuffer',
'Boolean',
'BigInt',
'DataView',
'Date',
'Error',
'EvalError',
'Float32Array',
'Float64Array',
'Function',
'Generator',
'GeneratorFunction',
'Infinity',
'Int16Array',
'Int32Array',
'Int8Array',
'InternalError',
'Intl',
'JSON',
'Map',
'Math',
'NaN',
'Number',
'Object',
'Promise',
'Proxy',
'RangeError',
'ReferenceError',
'Reflect',
'RegExp',
'Set',
'String',
'Symbol',
'SyntaxError',
'TypeError',
'URIError',
'Uint16Array',
'Uint32Array',
'Uint8Array',
'Uint8ClampedArray',
'WeakMap',
'WeakSet',
'arguments',
'console',
'expect',
'isNaN',
'jest',
'parseFloat',
'parseInt',
'exports',
'require',
'module',
'__filename',
'__dirname',
'undefined',
...Object.getOwnPropertyNames(globalThis),
].sort(),
);
const IDVisitor = {
ReferencedIdentifier(
path: NodePath<Identifier>,
{ids}: {ids: Set<NodePath<Identifier>>},
) {
ids.add(path);
},
denylist: [
'TypeAnnotation',
'TSTypeAnnotation',
'TSTypeQuery',
'TSTypeReference',
],
};
const FUNCTIONS = Object.create(null) as Record<
string,
<T extends Node>(args: Array<NodePath<T>>) => boolean
>;
FUNCTIONS.mock = args => {
if (args.length === 1) {
return args[0].isStringLiteral() || args[0].isLiteral();
} else if (args.length === 2 || args.length === 3) {
const moduleFactory = args[1];
if (!moduleFactory.isFunction()) {
throw moduleFactory.buildCodeFrameError(
'The second argument of `jest.mock` must be an inline function.\n',
TypeError,
);
}
const ids = new Set<NodePath<Identifier>>();
const parentScope = moduleFactory.parentPath.scope;
// @ts-expect-error: ReferencedIdentifier and denylist are not known on visitors
moduleFactory.traverse(IDVisitor, {ids});
for (const id of ids) {
const {name} = id.node;
let found = false;
let scope = id.scope;
while (scope !== parentScope) {
if (scope.bindings[name] != null) {
found = true;
break;
}
scope = scope.parent;
}
if (!found) {
let isAllowedIdentifier =
(scope.hasGlobal(name) && ALLOWED_IDENTIFIERS.has(name)) ||
/^mock/i.test(name) ||
// Allow istanbul's coverage variable to pass.
/^(?:__)?cov/.test(name);
if (!isAllowedIdentifier) {
const binding = scope.bindings[name];
if (binding?.path.isVariableDeclarator()) {
const {node} = binding.path;
const initNode = node.init;
if (initNode && binding.constant && scope.isPure(initNode, true)) {
hoistedVariables.add(node);
isAllowedIdentifier = true;
}
} else if (binding?.path.isImportSpecifier()) {
const importDecl = binding.path
.parentPath as NodePath<ImportDeclaration>;
const imported = binding.path.node.imported;
if (
importDecl.node.source.value === JEST_GLOBALS_MODULE_NAME &&
(isIdentifier(imported) ? imported.name : imported.value) ===
JEST_GLOBALS_MODULE_JEST_EXPORT_NAME
) {
isAllowedIdentifier = true;
// Imports are already hoisted, so we don't need to add it
// to hoistedVariables.
}
}
}
if (!isAllowedIdentifier) {
throw id.buildCodeFrameError(
'The module factory of `jest.mock()` is not allowed to ' +
'reference any out-of-scope variables.\n' +
`Invalid variable access: ${name}\n` +
`Allowed objects: ${[...ALLOWED_IDENTIFIERS].join(', ')}.\n` +
'Note: This is a precaution to guard against uninitialized mock ' +
'variables. If it is ensured that the mock is required lazily, ' +
'variable names prefixed with `mock` (case insensitive) are permitted.\n',
ReferenceError,
);
}
}
}
return true;
}
return false;
};
FUNCTIONS.unmock = args => args.length === 1 && args[0].isStringLiteral();
FUNCTIONS.deepUnmock = args => args.length === 1 && args[0].isStringLiteral();
FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = args =>
args.length === 0;
const createJestObjectGetter = statement`
function GETTER_NAME() {
const { JEST_GLOBALS_MODULE_JEST_EXPORT_NAME } = require("JEST_GLOBALS_MODULE_NAME");
GETTER_NAME = () => JEST_GLOBALS_MODULE_JEST_EXPORT_NAME;
return JEST_GLOBALS_MODULE_JEST_EXPORT_NAME;
}
`;
const isJestObject = (
expression: NodePath<Expression | Super>,
): expression is NodePath<Identifier | MemberExpression> => {
// global
if (
expression.isIdentifier() &&
expression.node.name === JEST_GLOBAL_NAME &&
!expression.scope.hasBinding(JEST_GLOBAL_NAME)
) {
return true;
}
// import { jest } from '@jest/globals'
if (
expression.referencesImport(
JEST_GLOBALS_MODULE_NAME,
JEST_GLOBALS_MODULE_JEST_EXPORT_NAME,
)
) {
return true;
}
// import * as JestGlobals from '@jest/globals'
if (
expression.isMemberExpression() &&
!expression.node.computed &&
expression
.get<'object'>('object')
.referencesImport(JEST_GLOBALS_MODULE_NAME, '*') &&
expression.node.property.type === 'Identifier' &&
expression.node.property.name === JEST_GLOBALS_MODULE_JEST_EXPORT_NAME
) {
return true;
}
return false;
};
type JestObjInfo = {
hoist: boolean;
path: NodePath<Expression>;
};
const extractJestObjExprIfHoistable = (expr: NodePath): JestObjInfo | null => {
if (!expr.isCallExpression()) {
return null;
}
const callee = expr.get<'callee'>('callee');
const args = expr.get<'arguments'>('arguments');
if (!callee.isMemberExpression() || callee.node.computed) {
return null;
}
const object = callee.get<'object'>('object');
const property = callee.get<'property'>('property') as NodePath<Identifier>;
const propertyName = property.node.name;
const jestObjExpr = isJestObject(object)
? object
: // The Jest object could be returned from another call since the functions are all chainable.
extractJestObjExprIfHoistable(object)?.path;
if (!jestObjExpr) {
return null;
}
// Important: Call the function check last
// It might throw an error to display to the user,
// which should only happen if we're already sure it's a call on the Jest object.
const functionIsHoistable = FUNCTIONS[propertyName]?.(args) ?? false;
let functionHasHoistableScope = functionIsHoistable;
for (
let path: NodePath<Node> | null = expr;
path && !functionHasHoistableScope;
path = path.parentPath
) {
functionHasHoistableScope = hoistedJestExpressions.has(
// @ts-expect-error: it's ok if path.node is not an Expression, .has will
// just return false.
path.node,
);
}
if (functionHasHoistableScope) {
hoistedJestExpressions.add(expr.node);
return {
hoist: functionIsHoistable,
path: jestObjExpr,
};
}
return null;
};
function visitBlock(block: NodePath<BlockStatement> | NodePath<Program>) {
// use a temporary empty statement instead of the real first statement, which may itself be hoisted
const [varsHoistPoint, callsHoistPoint] = block.unshiftContainer<
BlockStatement | Program,
'body',
[EmptyStatement, EmptyStatement]
>('body', [emptyStatement(), emptyStatement()]);
block.traverse({
CallExpression: visitCallExpr,
VariableDeclarator: visitVariableDeclarator,
// do not traverse into nested blocks, or we'll hoist calls in there out to this block
denylist: ['BlockStatement'],
});
callsHoistPoint.remove();
varsHoistPoint.remove();
function visitCallExpr(callExpr: NodePath<CallExpression>) {
if (hoistedJestGetters.has(callExpr.node)) {
const mockStmt = callExpr.getStatementParent();
if (mockStmt) {
const mockStmtParent = mockStmt.parentPath;
if (mockStmtParent.isBlock()) {
const mockStmtNode = mockStmt.node;
mockStmt.remove();
callsHoistPoint.insertBefore(mockStmtNode);
}
}
}
}
function visitVariableDeclarator(varDecl: NodePath<VariableDeclarator>) {
if (hoistedVariables.has(varDecl.node)) {
// should be assert function, but it's not. So let's cast below
varDecl.parentPath.assertVariableDeclaration();
const {kind, declarations} = varDecl.parent as VariableDeclaration;
if (declarations.length === 1) {
varDecl.parentPath.remove();
} else {
varDecl.remove();
}
varsHoistPoint.insertBefore(variableDeclaration(kind, [varDecl.node]));
}
}
}
/* eslint-disable sort-keys */
export default function jestHoist(): PluginObj<{
declareJestObjGetterIdentifier: () => Identifier;
jestObjGetterIdentifier?: Identifier;
}> {
return {
pre({path: program}) {
this.declareJestObjGetterIdentifier = () => {
if (this.jestObjGetterIdentifier) {
return this.jestObjGetterIdentifier;
}
this.jestObjGetterIdentifier =
program.scope.generateUidIdentifier('getJestObj');
program.unshiftContainer('body', [
createJestObjectGetter({
GETTER_NAME: this.jestObjGetterIdentifier.name,
JEST_GLOBALS_MODULE_JEST_EXPORT_NAME,
JEST_GLOBALS_MODULE_NAME,
}),
]);
return this.jestObjGetterIdentifier;
};
},
visitor: {
ExpressionStatement(exprStmt) {
const jestObjInfo = extractJestObjExprIfHoistable(
exprStmt.get('expression'),
);
if (jestObjInfo) {
const jestCallExpr = callExpression(
this.declareJestObjGetterIdentifier(),
[],
);
jestObjInfo.path.replaceWith(jestCallExpr);
if (jestObjInfo.hoist) {
hoistedJestGetters.add(jestCallExpr);
}
}
},
},
// in `post` to make sure we come after an import transform and can unshift above the `require`s
post({path: program}) {
visitBlock(program);
program.traverse({BlockStatement: visitBlock});
},
};
}
/* eslint-enable */