/
parseJestFnCall.ts
411 lines (344 loc) · 9.43 KB
/
parseJestFnCall.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
import { AST_NODE_TYPES, TSESLint, TSESTree } from '@typescript-eslint/utils';
import {
AccessorNode,
DescribeAlias,
HookName,
TestCaseName,
getAccessorValue,
getStringValue,
isIdentifier,
isStringNode,
isSupportedAccessor,
} from '../utils';
export const isTypeOfJestFnCall = (
node: TSESTree.CallExpression,
scope: TSESLint.Scope.Scope,
types: JestFnType[],
): boolean => {
const jestFnCall = parseJestFnCall(node, scope);
return jestFnCall !== null && types.includes(jestFnCall.type);
};
export function getNodeChain(node: TSESTree.Node): AccessorNode[] {
if (isSupportedAccessor(node)) {
return [node];
}
switch (node.type) {
case AST_NODE_TYPES.TaggedTemplateExpression:
return getNodeChain(node.tag);
case AST_NODE_TYPES.MemberExpression:
return [...getNodeChain(node.object), ...getNodeChain(node.property)];
case AST_NODE_TYPES.NewExpression:
case AST_NODE_TYPES.CallExpression:
return getNodeChain(node.callee);
}
return [];
}
export interface ResolvedJestFnWithNode extends ResolvedJestFn {
node: AccessorNode;
}
type JestFnType = 'hook' | 'describe' | 'test' | 'expect' | 'jest' | 'unknown';
const determineJestFnType = (name: string): JestFnType => {
// if (name === 'expect') {
// return 'expect';
// }
if (name === 'jest') {
return 'jest';
}
if (DescribeAlias.hasOwnProperty(name)) {
return 'describe';
}
if (TestCaseName.hasOwnProperty(name)) {
return 'test';
}
/* istanbul ignore else */
if (HookName.hasOwnProperty(name)) {
return 'hook';
}
/* istanbul ignore next */
return 'unknown';
};
export interface ParsedJestFnCall {
/**
* The name of the underlying Jest function that is being called.
* This is the result of `(head.original ?? head.local)`.
*/
name: string;
type: JestFnType;
head: ResolvedJestFnWithNode;
members: AccessorNode[];
}
const ValidJestFnCallChains = [
'afterAll',
'afterEach',
'beforeAll',
'beforeEach',
'describe',
'describe.each',
'describe.only',
'describe.only.each',
'describe.skip',
'describe.skip.each',
'fdescribe',
'fdescribe.each',
'xdescribe',
'xdescribe.each',
'it',
'it.concurrent',
'it.concurrent.each',
'it.concurrent.only.each',
'it.concurrent.skip.each',
'it.each',
'it.failing',
'it.only',
'it.only.each',
'it.only.failing',
'it.skip',
'it.skip.each',
'it.skip.failing',
'it.todo',
'fit',
'fit.each',
'fit.failing',
'xit',
'xit.each',
'xit.failing',
'test',
'test.concurrent',
'test.concurrent.each',
'test.concurrent.only.each',
'test.concurrent.skip.each',
'test.each',
'test.failing',
'test.only',
'test.only.each',
'test.only.failing',
'test.skip',
'test.skip.each',
'test.skip.failing',
'test.todo',
'xtest',
'xtest.each',
'xtest.failing',
// todo: check if actually valid (not in docs)
'test.concurrent.skip',
'test.concurrent.only',
'it.concurrent.skip',
'it.concurrent.only',
];
export const parseJestFnCall = (
node: TSESTree.CallExpression,
scope: TSESLint.Scope.Scope,
): ParsedJestFnCall | null => {
// ensure that we're at the "top" of the function call chain otherwise when
// parsing e.g. x().y.z(), we'll incorrectly find & parse "x()" even though
// the full chain is not a valid jest function call chain
if (
node.parent?.type === AST_NODE_TYPES.CallExpression ||
node.parent?.type === AST_NODE_TYPES.MemberExpression
) {
return null;
}
const chain = getNodeChain(node);
if (chain.length === 0) {
return null;
}
// ensure that the only call expression in the chain is at the end
if (
chain
.slice(0, chain.length - 1)
.some(nod => nod.parent?.type === AST_NODE_TYPES.CallExpression)
) {
return null;
}
const [first, ...rest] = chain;
const lastNode = chain[chain.length - 1];
// if we're an `each()`, ensure we're the outer CallExpression (i.e `.each()()`)
if (isSupportedAccessor(lastNode, 'each')) {
if (
node.callee.type !== AST_NODE_TYPES.CallExpression &&
node.callee.type !== AST_NODE_TYPES.TaggedTemplateExpression
) {
return null;
}
}
const resolved = resolveToJestFn(scope, getAccessorValue(first));
// we're not a jest function
if (!resolved) {
return null;
}
const name = resolved.original ?? resolved.local;
const links = [name, ...rest.map(link => getAccessorValue(link))];
if (name !== 'jest' && !ValidJestFnCallChains.includes(links.join('.'))) {
return null;
}
return {
name,
type: determineJestFnType(name),
head: { ...resolved, node: first },
members: rest,
};
};
interface ImportDetails {
source: string;
local: string;
imported: string;
}
const describeImportDefAsImport = (
def: TSESLint.Scope.Definitions.ImportBindingDefinition,
): ImportDetails | null => {
if (def.parent.type === AST_NODE_TYPES.TSImportEqualsDeclaration) {
return null;
}
if (def.node.type !== AST_NODE_TYPES.ImportSpecifier) {
return null;
}
// we only care about value imports
if (def.parent.importKind === 'type') {
return null;
}
return {
source: def.parent.source.value,
imported: def.node.imported.name,
local: def.node.local.name,
};
};
/**
* Attempts to find the node that represents the import source for the
* given expression node, if it looks like it's an import.
*
* If no such node can be found (e.g. because the expression doesn't look
* like an import), then `null` is returned instead.
*/
const findImportSourceNode = (
node: TSESTree.Expression,
): TSESTree.Node | null => {
if (node.type === AST_NODE_TYPES.AwaitExpression) {
if (node.argument.type === AST_NODE_TYPES.ImportExpression) {
return (node.argument as TSESTree.ImportExpression).source;
}
return null;
}
if (
node.type === AST_NODE_TYPES.CallExpression &&
isIdentifier(node.callee, 'require')
) {
return node.arguments[0] ?? null;
}
return null;
};
const describeVariableDefAsImport = (
def: TSESLint.Scope.Definitions.VariableDefinition,
): ImportDetails | null => {
// make sure that we've actually being assigned a value
if (!def.node.init) {
return null;
}
const sourceNode = findImportSourceNode(def.node.init);
if (!sourceNode || !isStringNode(sourceNode)) {
return null;
}
if (def.name.parent?.type !== AST_NODE_TYPES.Property) {
return null;
}
if (!isSupportedAccessor(def.name.parent.key)) {
return null;
}
return {
source: getStringValue(sourceNode),
imported: getAccessorValue(def.name.parent.key),
local: def.name.name,
};
};
/**
* Attempts to describe a definition as an import if possible.
*
* If the definition is an import binding, it's described as you'd expect.
* If the definition is a variable, then we try and determine if it's either
* a dynamic `import()` or otherwise a call to `require()`.
*
* If it's neither of these, `null` is returned to indicate that the definition
* is not describable as an import of any kind.
*/
const describePossibleImportDef = (def: TSESLint.Scope.Definition) => {
if (def.type === 'Variable') {
return describeVariableDefAsImport(def);
}
if (def.type === 'ImportBinding') {
return describeImportDefAsImport(def);
}
return null;
};
const collectReferences = (scope: TSESLint.Scope.Scope) => {
const locals = new Set();
const imports = new Map<string, ImportDetails>();
const unresolved = new Set();
let currentScope: TSESLint.Scope.Scope | null = scope;
while (currentScope !== null) {
for (const ref of currentScope.variables) {
if (ref.defs.length === 0) {
continue;
}
const def = ref.defs[ref.defs.length - 1];
const importDetails = describePossibleImportDef(def);
if (importDetails) {
imports.set(importDetails.local, importDetails);
continue;
}
locals.add(ref.name);
}
for (const ref of currentScope.through) {
unresolved.add(ref.identifier.name);
}
currentScope = currentScope.upper;
}
return { locals, imports, unresolved };
};
interface ResolvedJestFn {
original: string | null;
local: string;
type: 'import' | 'global';
}
const resolveToJestFn = (
scope: TSESLint.Scope.Scope,
identifier: string,
): ResolvedJestFn | null => {
const references = collectReferences(scope);
const maybeImport = references.imports.get(identifier);
if (maybeImport) {
// the identifier is imported from @jest/globals,
// so return the original import name
if (maybeImport.source === '@jest/globals') {
return {
original: maybeImport.imported,
local: maybeImport.local,
type: 'import',
};
}
return null;
}
// the identifier was found as a local variable or function declaration
// meaning it's not a function from jest
if (references.locals.has(identifier)) {
return null;
}
return {
original: null,
local: identifier,
type: 'global',
};
};
export const scopeHasLocalReference = (
scope: TSESLint.Scope.Scope,
referenceName: string,
) => {
const references = collectReferences(scope);
return (
// referenceName was found as a local variable or function declaration.
references.locals.has(referenceName) ||
// referenceName was found as an imported identifier
references.imports.has(referenceName) ||
// referenceName was not found as an unresolved reference,
// meaning it is likely not an implicit global reference.
!references.unresolved.has(referenceName)
);
};