/
parseJestFnCall.ts
581 lines (483 loc) · 13.7 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
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
import { AST_NODE_TYPES, TSESLint, TSESTree } from '@typescript-eslint/utils';
import {
AccessorNode,
DescribeAlias,
HookName,
KnownMemberExpression,
ModifierName,
TestCaseName,
findTopMostCallExpression,
getAccessorValue,
getStringValue,
isIdentifier,
isStringNode,
isSupportedAccessor,
} from '../utils';
export const isTypeOfJestFnCall = (
node: TSESTree.CallExpression,
context: TSESLint.RuleContext<string, unknown[]>,
types: JestFnType[],
): boolean => {
const jestFnCall = parseJestFnCall(node, context);
return jestFnCall !== null && types.includes(jestFnCall.type);
};
const joinChains = (
a: AccessorNode[] | null,
b: AccessorNode[] | null,
): AccessorNode[] | null => (a && b ? [...a, ...b] : null);
export function getNodeChain(node: TSESTree.Node): AccessorNode[] | null {
if (isSupportedAccessor(node)) {
return [node];
}
switch (node.type) {
case AST_NODE_TYPES.TaggedTemplateExpression:
return getNodeChain(node.tag);
case AST_NODE_TYPES.MemberExpression:
return joinChains(getNodeChain(node.object), getNodeChain(node.property));
case AST_NODE_TYPES.CallExpression:
return getNodeChain(node.callee);
}
return null;
}
export interface ResolvedJestFnWithNode extends ResolvedJestFn {
node: AccessorNode;
}
export 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';
};
interface BaseParsedJestFnCall {
/**
* 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: KnownMemberExpressionProperty[];
}
interface ParsedGeneralJestFnCall extends BaseParsedJestFnCall {
type: Exclude<JestFnType, 'expect'>;
}
export interface ParsedExpectFnCall
extends BaseParsedJestFnCall,
ModifiersAndMatcher {
type: 'expect';
}
export type ParsedJestFnCall = ParsedGeneralJestFnCall | ParsedExpectFnCall;
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',
];
declare module '@typescript-eslint/utils/dist/ts-eslint' {
export interface SharedConfigurationSettings {
jest?: {
globalAliases?: Record<string, string[]>;
version?: number | string;
};
}
}
const resolvePossibleAliasedGlobal = (
global: string,
context: TSESLint.RuleContext<string, unknown[]>,
) => {
const globalAliases = context.settings.jest?.globalAliases ?? {};
const alias = Object.entries(globalAliases).find(([, aliases]) =>
aliases.includes(global),
);
if (alias) {
return alias[0];
}
return null;
};
const parseJestFnCallCache = new WeakMap<
TSESTree.CallExpression,
ParsedJestFnCall | string | null
>();
export const parseJestFnCall = (
node: TSESTree.CallExpression,
context: TSESLint.RuleContext<string, unknown[]>,
): ParsedJestFnCall | null => {
const jestFnCall = parseJestFnCallWithReason(node, context);
if (typeof jestFnCall === 'string') {
return null;
}
return jestFnCall;
};
export const parseJestFnCallWithReason = (
node: TSESTree.CallExpression,
context: TSESLint.RuleContext<string, unknown[]>,
): ParsedJestFnCall | string | null => {
let parsedJestFnCall = parseJestFnCallCache.get(node);
if (parsedJestFnCall) {
return parsedJestFnCall;
}
parsedJestFnCall = parseJestFnCallWithReasonInner(node, context);
parseJestFnCallCache.set(node, parsedJestFnCall);
return parsedJestFnCall;
};
const parseJestFnCallWithReasonInner = (
node: TSESTree.CallExpression,
context: TSESLint.RuleContext<string, unknown[]>,
): ParsedJestFnCall | string | null => {
const chain = getNodeChain(node);
if (!chain?.length) {
return null;
}
const [first, ...rest] = chain;
const lastLink = getAccessorValue(chain[chain.length - 1]);
// if we're an `each()`, ensure we're the outer CallExpression (i.e `.each()()`)
if (lastLink === 'each') {
if (
node.callee.type !== AST_NODE_TYPES.CallExpression &&
node.callee.type !== AST_NODE_TYPES.TaggedTemplateExpression
) {
return null;
}
}
if (
node.callee.type === AST_NODE_TYPES.TaggedTemplateExpression &&
lastLink !== 'each'
) {
return null;
}
const resolved = resolveToJestFn(context, 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' &&
name !== 'expect' &&
!ValidJestFnCallChains.includes(links.join('.'))
) {
return null;
}
const parsedJestFnCall: Omit<ParsedJestFnCall, 'type'> = {
name,
head: { ...resolved, node: first },
// every member node must have a member expression as their parent
// in order to be part of the call chain we're parsing
members: rest as KnownMemberExpressionProperty[],
};
const type = determineJestFnType(name);
if (type === 'expect') {
const result = parseJestExpectCall(parsedJestFnCall);
// if the `expect` call chain is not valid, only report on the topmost node
// since all members in the chain are likely to get flagged for some reason
if (
typeof result === 'string' &&
findTopMostCallExpression(node) !== node
) {
return null;
}
if (result === 'matcher-not-found') {
if (node.parent?.type === AST_NODE_TYPES.MemberExpression) {
return 'matcher-not-called';
}
}
return result;
}
// check that every link in the chain except the last is a member expression
if (
chain
.slice(0, chain.length - 1)
.some(nod => nod.parent?.type !== AST_NODE_TYPES.MemberExpression)
) {
return 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;
}
return { ...parsedJestFnCall, type };
};
type KnownMemberExpressionProperty<Specifics extends string = string> =
AccessorNode<Specifics> & { parent: KnownMemberExpression<Specifics> };
interface ModifiersAndMatcher {
modifiers: KnownMemberExpressionProperty[];
matcher: KnownMemberExpressionProperty;
/** The arguments that are being passed to the `matcher` */
args: TSESTree.CallExpression['arguments'];
}
const findModifiersAndMatcher = (
members: KnownMemberExpressionProperty[],
): ModifiersAndMatcher | string => {
const modifiers: KnownMemberExpressionProperty[] = [];
for (const member of members) {
// check if the member is being called, which means it is the matcher
// (and also the end of the entire "expect" call chain)
if (
member.parent?.type === AST_NODE_TYPES.MemberExpression &&
member.parent.parent?.type === AST_NODE_TYPES.CallExpression
) {
return {
matcher: member,
args: member.parent.parent.arguments,
modifiers,
};
}
// otherwise, it should be a modifier
const name = getAccessorValue(member);
if (modifiers.length === 0) {
// the first modifier can be any of the three modifiers
if (!ModifierName.hasOwnProperty(name)) {
return 'modifier-unknown';
}
} else if (modifiers.length === 1) {
// the second modifier can only be "not"
if (name !== ModifierName.not) {
return 'modifier-unknown';
}
const firstModifier = getAccessorValue(modifiers[0]);
// and the first modifier has to be either "resolves" or "rejects"
if (
firstModifier !== ModifierName.resolves &&
firstModifier !== ModifierName.rejects
) {
return 'modifier-unknown';
}
} else {
return 'modifier-unknown';
}
modifiers.push(member);
}
// this will only really happen if there are no members
return 'matcher-not-found';
};
const parseJestExpectCall = (
typelessParsedJestFnCall: Omit<ParsedJestFnCall, 'type'>,
): ParsedExpectFnCall | string => {
const modifiersAndMatcher = findModifiersAndMatcher(
typelessParsedJestFnCall.members,
);
if (typeof modifiersAndMatcher === 'string') {
return modifiersAndMatcher;
}
return {
...typelessParsedJestFnCall,
type: 'expect',
...modifiersAndMatcher,
};
};
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.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;
};
export const resolveScope = (
scope: TSESLint.Scope.Scope,
identifier: string,
): ImportDetails | 'local' | null => {
let currentScope: TSESLint.Scope.Scope | null = scope;
while (currentScope !== null) {
const ref = currentScope.set.get(identifier);
if (ref && ref.defs.length > 0) {
const def = ref.defs[ref.defs.length - 1];
const importDetails = describePossibleImportDef(def);
if (importDetails?.local === identifier) {
return importDetails;
}
return 'local';
}
currentScope = currentScope.upper;
}
return null;
};
interface ResolvedJestFn {
original: string | null;
local: string;
type: 'import' | 'global';
}
const resolveToJestFn = (
context: TSESLint.RuleContext<string, unknown[]>,
identifier: string,
): ResolvedJestFn | null => {
const maybeImport = resolveScope(context.getScope(), identifier);
// the identifier was found as a local variable or function declaration
// meaning it's not a function from jest
if (maybeImport === 'local') {
return null;
}
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;
}
return {
original: resolvePossibleAliasedGlobal(identifier, context),
local: identifier,
type: 'global',
};
};