-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathdetect-testing-library-utils.ts
564 lines (506 loc) · 19.7 KB
/
detect-testing-library-utils.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
import {
ASTUtils,
TSESLint,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import {
getAssertNodeInfo,
getImportModuleName,
getPropertyIdentifierNode,
getReferenceNode,
ImportModuleNode,
isImportDeclaration,
isImportNamespaceSpecifier,
isImportSpecifier,
isLiteral,
isMemberExpression,
isProperty,
} from './node-utils';
import {
ABSENCE_MATCHERS,
ASYNC_UTILS,
PRESENCE_MATCHERS,
ALL_QUERIES_COMBINATIONS,
} from './utils';
export type TestingLibrarySettings = {
'testing-library/utils-module'?: string;
'testing-library/filename-pattern'?: string;
'testing-library/custom-renders'?: string[];
};
export type TestingLibraryContext<
TOptions extends readonly unknown[],
TMessageIds extends string
> = Readonly<
TSESLint.RuleContext<TMessageIds, TOptions> & {
settings: TestingLibrarySettings;
}
>;
export type EnhancedRuleCreate<
TOptions extends readonly unknown[],
TMessageIds extends string,
TRuleListener extends TSESLint.RuleListener = TSESLint.RuleListener
> = (
context: TestingLibraryContext<TOptions, TMessageIds>,
optionsWithDefault: Readonly<TOptions>,
detectionHelpers: Readonly<DetectionHelpers>
) => TRuleListener;
// Helpers methods
type GetTestingLibraryImportNodeFn = () => ImportModuleNode | null;
type GetCustomModuleImportNodeFn = () => ImportModuleNode | null;
type GetTestingLibraryImportNameFn = () => string | undefined;
type GetCustomModuleImportNameFn = () => string | undefined;
type IsTestingLibraryImportedFn = () => boolean;
type IsValidFilenameFn = () => boolean;
type IsGetQueryVariantFn = (node: TSESTree.Identifier) => boolean;
type IsQueryQueryVariantFn = (node: TSESTree.Identifier) => boolean;
type IsFindQueryVariantFn = (node: TSESTree.Identifier) => boolean;
type IsSyncQueryFn = (node: TSESTree.Identifier) => boolean;
type IsAsyncQueryFn = (node: TSESTree.Identifier) => boolean;
type IsCustomQueryFn = (node: TSESTree.Identifier) => boolean;
type IsAsyncUtilFn = (node: TSESTree.Identifier) => boolean;
type IsFireEventMethodFn = (node: TSESTree.Identifier) => boolean;
type IsRenderUtilFn = (node: TSESTree.Identifier) => boolean;
type IsPresenceAssertFn = (node: TSESTree.MemberExpression) => boolean;
type IsAbsenceAssertFn = (node: TSESTree.MemberExpression) => boolean;
type CanReportErrorsFn = () => boolean;
type FindImportedUtilSpecifierFn = (
specifierName: string
) => TSESTree.ImportClause | TSESTree.Identifier | undefined;
type IsNodeComingFromTestingLibraryFn = (
node: TSESTree.MemberExpression | TSESTree.Identifier
) => boolean;
export interface DetectionHelpers {
getTestingLibraryImportNode: GetTestingLibraryImportNodeFn;
getCustomModuleImportNode: GetCustomModuleImportNodeFn;
getTestingLibraryImportName: GetTestingLibraryImportNameFn;
getCustomModuleImportName: GetCustomModuleImportNameFn;
isTestingLibraryImported: IsTestingLibraryImportedFn;
isValidFilename: IsValidFilenameFn;
isGetQueryVariant: IsGetQueryVariantFn;
isQueryQueryVariant: IsQueryQueryVariantFn;
isFindQueryVariant: IsFindQueryVariantFn;
isSyncQuery: IsSyncQueryFn;
isAsyncQuery: IsAsyncQueryFn;
isCustomQuery: IsCustomQueryFn;
isAsyncUtil: IsAsyncUtilFn;
isFireEventMethod: IsFireEventMethodFn;
isRenderUtil: IsRenderUtilFn;
isPresenceAssert: IsPresenceAssertFn;
isAbsenceAssert: IsAbsenceAssertFn;
canReportErrors: CanReportErrorsFn;
findImportedUtilSpecifier: FindImportedUtilSpecifierFn;
isNodeComingFromTestingLibrary: IsNodeComingFromTestingLibraryFn;
}
const DEFAULT_FILENAME_PATTERN = '^.*\\.(test|spec)\\.[jt]sx?$';
const FIRE_EVENT_NAME = 'fireEvent';
const RENDER_NAME = 'render';
/**
* Enhances a given rule `create` with helpers to detect Testing Library utils.
*/
export function detectTestingLibraryUtils<
TOptions extends readonly unknown[],
TMessageIds extends string,
TRuleListener extends TSESLint.RuleListener = TSESLint.RuleListener
>(ruleCreate: EnhancedRuleCreate<TOptions, TMessageIds, TRuleListener>) {
return (
context: TestingLibraryContext<TOptions, TMessageIds>,
optionsWithDefault: Readonly<TOptions>
): TSESLint.RuleListener => {
let importedTestingLibraryNode: ImportModuleNode | null = null;
let importedCustomModuleNode: ImportModuleNode | null = null;
// Init options based on shared ESLint settings
const customModule = context.settings['testing-library/utils-module'];
const filenamePattern =
context.settings['testing-library/filename-pattern'] ??
DEFAULT_FILENAME_PATTERN;
const customRenders = context.settings['testing-library/custom-renders'];
/**
* Small method to extract common checks to determine whether a node is
* related to Testing Library or not.
*/
function isTestingLibraryUtil(
node: TSESTree.Identifier,
isUtilCallback: (identifierNode: TSESTree.Identifier) => boolean
): boolean {
if (!isUtilCallback(node)) {
return false;
}
const referenceNode = getReferenceNode(node);
const referenceNodeIdentifier = getPropertyIdentifierNode(referenceNode);
return (
isAggressiveModuleReportingEnabled() ||
isNodeComingFromTestingLibrary(referenceNodeIdentifier)
);
}
/**
* Determines whether aggressive module reporting is enabled or not.
*
* This aggressive reporting mechanism is considered as enabled when custom
* module is not set, so we need to assume everything matching Testing
* Library utils is related to Testing Library no matter from where module
* they are coming from. Otherwise, this aggressive reporting mechanism is
* opted-out in favour to report only those utils coming from Testing
* Library package or custom module set up on settings.
*/
const isAggressiveModuleReportingEnabled = () => !customModule;
/**
* Determines whether aggressive render reporting is enabled or not.
*
* This aggressive reporting mechanism is considered as enabled when custom
* renders are not set, so we need to assume every method containing
* "render" is a valid Testing Library `render`. Otherwise, this aggressive
* reporting mechanism is opted-out in favour to report only `render` or
* names set up on custom renders setting.
*/
const isAggressiveRenderReportingEnabled = () =>
!Array.isArray(customRenders) || customRenders.length === 0;
// Helpers for Testing Library detection.
const getTestingLibraryImportNode: GetTestingLibraryImportNodeFn = () => {
return importedTestingLibraryNode;
};
const getCustomModuleImportNode: GetCustomModuleImportNodeFn = () => {
return importedCustomModuleNode;
};
const getTestingLibraryImportName: GetTestingLibraryImportNameFn = () => {
return getImportModuleName(importedTestingLibraryNode);
};
const getCustomModuleImportName: GetCustomModuleImportNameFn = () => {
return getImportModuleName(importedCustomModuleNode);
};
/**
* Determines whether Testing Library utils are imported or not for
* current file being analyzed.
*
* By default, it is ALWAYS considered as imported. This is what we call
* "aggressive reporting" so we don't miss TL utils reexported from
* custom modules.
*
* However, there is a setting to customize the module where TL utils can
* be imported from: "testing-library/utils-module". If this setting is enabled,
* then this method will return `true` ONLY IF a testing-library package
* or custom module are imported.
*/
const isTestingLibraryImported: IsTestingLibraryImportedFn = () => {
return (
isAggressiveModuleReportingEnabled() ||
!!importedTestingLibraryNode ||
!!importedCustomModuleNode
);
};
/**
* Determines whether filename is valid or not for current file
* being analyzed based on "testing-library/filename-pattern" setting.
*/
const isValidFilename: IsValidFilenameFn = () => {
const fileName = context.getFilename();
return !!fileName.match(filenamePattern);
};
/**
* Determines whether a given node is `get*` query variant or not.
*/
const isGetQueryVariant: IsGetQueryVariantFn = (node) => {
return /^get(All)?By.+$/.test(node.name);
};
/**
* Determines whether a given node is `query*` query variant or not.
*/
const isQueryQueryVariant: IsQueryQueryVariantFn = (node) => {
return /^query(All)?By.+$/.test(node.name);
};
/**
* Determines whether a given node is `find*` query variant or not.
*/
const isFindQueryVariant: IsFindQueryVariantFn = (node) => {
return /^find(All)?By.+$/.test(node.name);
};
/**
* Determines whether a given node is sync query or not.
*/
const isSyncQuery: IsSyncQueryFn = (node) => {
return isGetQueryVariant(node) || isQueryQueryVariant(node);
};
/**
* Determines whether a given node is async query or not.
*/
const isAsyncQuery: IsAsyncQueryFn = (node) => {
return isFindQueryVariant(node);
};
const isCustomQuery: IsCustomQueryFn = (node) => {
return (
(isSyncQuery(node) || isAsyncQuery(node)) &&
!ALL_QUERIES_COMBINATIONS.includes(node.name)
);
};
/**
* Determines whether a given node is a valid async util or not.
*
* A node will be interpreted as a valid async util based on two conditions:
* the name matches with some Testing Library async util, and the node is
* coming from Testing Library module.
*
* The latter depends on Aggressive module reporting:
* if enabled, then it doesn't matter from where the given node was imported
* from as it will be considered part of Testing Library.
* Otherwise, it means `custom-module` has been set up, so only those nodes
* coming from Testing Library will be considered as valid.
*/
const isAsyncUtil: IsAsyncUtilFn = (node) => {
return isTestingLibraryUtil(node, (identifierNode) =>
ASYNC_UTILS.includes(identifierNode.name)
);
};
/**
* Determines whether a given node is fireEvent method or not
*/
const isFireEventMethod: IsFireEventMethodFn = (node) => {
const fireEventUtil = findImportedUtilSpecifier(FIRE_EVENT_NAME);
let fireEventUtilName: string | undefined;
if (fireEventUtil) {
fireEventUtilName = ASTUtils.isIdentifier(fireEventUtil)
? fireEventUtil.name
: fireEventUtil.local.name;
} else if (isAggressiveModuleReportingEnabled()) {
fireEventUtilName = FIRE_EVENT_NAME;
}
if (!fireEventUtilName) {
return false;
}
const parentMemberExpression:
| TSESTree.MemberExpression
| undefined = isMemberExpression(node.parent) ? node.parent : undefined;
if (!parentMemberExpression) {
return false;
}
// make sure that given node it's not fireEvent object itself
if (
[fireEventUtilName, FIRE_EVENT_NAME].includes(node.name) ||
(ASTUtils.isIdentifier(parentMemberExpression.object) &&
parentMemberExpression.object.name === node.name)
) {
return false;
}
// check fireEvent.click() usage
const regularCall =
ASTUtils.isIdentifier(parentMemberExpression.object) &&
parentMemberExpression.object.name === fireEventUtilName;
// check testingLibraryUtils.fireEvent.click() usage
const wildcardCall =
isMemberExpression(parentMemberExpression.object) &&
ASTUtils.isIdentifier(parentMemberExpression.object.object) &&
parentMemberExpression.object.object.name === fireEventUtilName &&
ASTUtils.isIdentifier(parentMemberExpression.object.property) &&
parentMemberExpression.object.property.name === FIRE_EVENT_NAME;
return regularCall || wildcardCall;
};
/**
* Determines whether a given node is a valid render util or not.
*
* A node will be interpreted as a valid render based on two conditions:
* the name matches with a valid "render" option, and the node is coming
* from Testing Library module. This depends on:
*
* - Aggressive render reporting: if enabled, then every node name
* containing "render" will be assumed as Testing Library render util.
* Otherwise, it means `custom-modules` has been set up, so only those nodes
* named as "render" or some of the `custom-modules` options will be
* considered as Testing Library render util.
* - Aggressive module reporting: if enabled, then it doesn't matter from
* where the given node was imported from as it will be considered part of
* Testing Library. Otherwise, it means `custom-module` has been set up, so
* only those nodes coming from Testing Library will be considered as valid.
*/
const isRenderUtil: IsRenderUtilFn = (node) => {
return isTestingLibraryUtil(node, (identifierNode) => {
if (isAggressiveRenderReportingEnabled()) {
return identifierNode.name.toLowerCase().includes(RENDER_NAME);
}
return [RENDER_NAME, ...customRenders].includes(identifierNode.name);
});
};
/**
* Determines whether a given MemberExpression node is a presence assert
*
* Presence asserts could have shape of:
* - expect(element).toBeInTheDocument()
* - expect(element).not.toBeNull()
*/
const isPresenceAssert: IsPresenceAssertFn = (node) => {
const { matcher, isNegated } = getAssertNodeInfo(node);
if (!matcher) {
return false;
}
return isNegated
? ABSENCE_MATCHERS.includes(matcher)
: PRESENCE_MATCHERS.includes(matcher);
};
/**
* Determines whether a given MemberExpression node is an absence assert
*
* Absence asserts could have shape of:
* - expect(element).toBeNull()
* - expect(element).not.toBeInTheDocument()
*/
const isAbsenceAssert: IsAbsenceAssertFn = (node) => {
const { matcher, isNegated } = getAssertNodeInfo(node);
if (!matcher) {
return false;
}
return isNegated
? PRESENCE_MATCHERS.includes(matcher)
: ABSENCE_MATCHERS.includes(matcher);
};
/**
* Gets a string and verifies if it was imported/required by Testing Library
* related module.
*/
const findImportedUtilSpecifier: FindImportedUtilSpecifierFn = (
specifierName
) => {
const node = getCustomModuleImportNode() ?? getTestingLibraryImportNode();
if (!node) {
return null;
}
if (isImportDeclaration(node)) {
const namedExport = node.specifiers.find(
(n) => isImportSpecifier(n) && n.imported.name === specifierName
);
// it is "import { foo [as alias] } from 'baz'""
if (namedExport) {
return namedExport;
}
// it could be "import * as rtl from 'baz'"
return node.specifiers.find((n) => isImportNamespaceSpecifier(n));
} else {
const requireNode = node.parent as TSESTree.VariableDeclarator;
if (ASTUtils.isIdentifier(requireNode.id)) {
// this is const rtl = require('foo')
return requireNode.id;
}
// this should be const { something } = require('foo')
const destructuring = requireNode.id as TSESTree.ObjectPattern;
const property = destructuring.properties.find(
(n) =>
isProperty(n) &&
ASTUtils.isIdentifier(n.key) &&
n.key.name === specifierName
);
return (property as TSESTree.Property).key as TSESTree.Identifier;
}
};
/**
* Determines if file inspected meets all conditions to be reported by rules or not.
*/
const canReportErrors: CanReportErrorsFn = () => {
return isTestingLibraryImported() && isValidFilename();
};
/**
* Takes a MemberExpression or an Identifier and verifies if its name comes from the import in TL
* @param node a MemberExpression (in "foo.property" it would be property) or an Identifier
*/
const isNodeComingFromTestingLibrary: IsNodeComingFromTestingLibraryFn = (
node
) => {
const identifierName: string | undefined = getPropertyIdentifierNode(node)
.name;
return !!findImportedUtilSpecifier(identifierName);
};
const helpers: DetectionHelpers = {
getTestingLibraryImportNode,
getCustomModuleImportNode,
getTestingLibraryImportName,
getCustomModuleImportName,
isTestingLibraryImported,
isValidFilename,
isGetQueryVariant,
isQueryQueryVariant,
isFindQueryVariant,
isSyncQuery,
isAsyncQuery,
isCustomQuery,
isAsyncUtil,
isFireEventMethod,
isRenderUtil,
isPresenceAssert,
isAbsenceAssert,
canReportErrors,
findImportedUtilSpecifier,
isNodeComingFromTestingLibrary,
};
// Instructions for Testing Library detection.
const detectionInstructions: TSESLint.RuleListener = {
/**
* This ImportDeclaration rule listener will check if Testing Library related
* modules are imported. Since imports happen first thing in a file, it's
* safe to use `isImportingTestingLibraryModule` and `isImportingCustomModule`
* since they will have corresponding value already updated when reporting other
* parts of the file.
*/
ImportDeclaration(node: TSESTree.ImportDeclaration) {
// check only if testing library import not found yet so we avoid
// to override importedTestingLibraryNode after it's found
if (
!importedTestingLibraryNode &&
/testing-library/g.test(node.source.value as string)
) {
importedTestingLibraryNode = node;
}
// check only if custom module import not found yet so we avoid
// to override importedCustomModuleNode after it's found
if (
!importedCustomModuleNode &&
String(node.source.value).endsWith(customModule)
) {
importedCustomModuleNode = node;
}
},
// Check if Testing Library related modules are loaded with required.
[`CallExpression > Identifier[name="require"]`](
node: TSESTree.Identifier
) {
const callExpression = node.parent as TSESTree.CallExpression;
const { arguments: args } = callExpression;
if (
!importedTestingLibraryNode &&
args.some(
(arg) =>
isLiteral(arg) &&
typeof arg.value === 'string' &&
/testing-library/g.test(arg.value)
)
) {
importedTestingLibraryNode = callExpression;
}
if (
!importedCustomModuleNode &&
args.some(
(arg) =>
isLiteral(arg) &&
typeof arg.value === 'string' &&
arg.value.endsWith(customModule)
)
) {
importedCustomModuleNode = callExpression;
}
},
};
// update given rule to inject Testing Library detection
const ruleInstructions = ruleCreate(context, optionsWithDefault, helpers);
const enhancedRuleInstructions: TSESLint.RuleListener = {};
const allKeys = new Set(
Object.keys(detectionInstructions).concat(Object.keys(ruleInstructions))
);
// Iterate over ALL instructions keys so we can override original rule instructions
// to prevent their execution if conditions to report errors are not met.
allKeys.forEach((instruction) => {
enhancedRuleInstructions[instruction] = (node) => {
if (instruction in detectionInstructions) {
detectionInstructions[instruction](node);
}
if (canReportErrors() && ruleInstructions[instruction]) {
return ruleInstructions[instruction](node);
}
};
});
return enhancedRuleInstructions;
};
}