-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathdetect-testing-library-utils.ts
468 lines (415 loc) · 15.5 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
import {
ASTUtils,
TSESLint,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import {
getAssertNodeInfo,
getImportModuleName,
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/module'?: string;
'testing-library/filename-pattern'?: 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;
export type DetectionHelpers = {
getTestingLibraryImportNode: () => ImportModuleNode | null;
getCustomModuleImportNode: () => ImportModuleNode | null;
getTestingLibraryImportName: () => string | undefined;
getCustomModuleImportName: () => string | undefined;
isTestingLibraryImported: () => boolean;
isValidFilename: () => boolean;
isGetByQuery: (node: TSESTree.Identifier) => boolean;
isQueryByQuery: (node: TSESTree.Identifier) => boolean;
isFindByQuery: (node: TSESTree.Identifier) => boolean;
isSyncQuery: (node: TSESTree.Identifier) => boolean;
isAsyncQuery: (node: TSESTree.Identifier) => boolean;
isCustomQuery: (node: TSESTree.Identifier) => boolean;
isAsyncUtil: (node: TSESTree.Identifier) => boolean;
isFireEventMethod: (node: TSESTree.Identifier) => boolean;
isPresenceAssert: (node: TSESTree.MemberExpression) => boolean;
isAbsenceAssert: (node: TSESTree.MemberExpression) => boolean;
canReportErrors: () => boolean;
findImportedUtilSpecifier: (
specifierName: string
) => TSESTree.ImportClause | TSESTree.Identifier | undefined;
isNodeComingFromTestingLibrary: (
node: TSESTree.MemberExpression | TSESTree.Identifier
) => boolean;
};
const DEFAULT_FILENAME_PATTERN = '^.*\\.(test|spec)\\.[jt]sx?$';
const FIRE_EVENT_NAME = 'fireEvent';
/**
* 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/module'];
const filenamePattern =
context.settings['testing-library/filename-pattern'] ??
DEFAULT_FILENAME_PATTERN;
/**
* Determines whether aggressive reporting is enabled or not.
*
* Aggressive reporting is considered as enabled when:
* - custom module is not set (so we need to assume everything
* matching TL utils is related to TL no matter where it was imported from)
*/
const isAggressiveReportingEnabled = () => !customModule;
// Helpers for Testing Library detection.
const getTestingLibraryImportNode: DetectionHelpers['getTestingLibraryImportNode'] = () => {
return importedTestingLibraryNode;
};
const getCustomModuleImportNode: DetectionHelpers['getCustomModuleImportNode'] = () => {
return importedCustomModuleNode;
};
const getTestingLibraryImportName: DetectionHelpers['getTestingLibraryImportName'] = () => {
return getImportModuleName(importedTestingLibraryNode);
};
const getCustomModuleImportName: DetectionHelpers['getCustomModuleImportName'] = () => {
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/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: DetectionHelpers['isTestingLibraryImported'] = () => {
if (isAggressiveReportingEnabled()) {
return true;
}
return !!importedTestingLibraryNode || !!importedCustomModuleNode;
};
/**
* Determines whether filename is valid or not for current file
* being analyzed based on "testing-library/filename-pattern" setting.
*/
const isValidFilename: DetectionHelpers['isValidFilename'] = () => {
const fileName = context.getFilename();
return !!fileName.match(filenamePattern);
};
/**
* Determines whether a given node is `getBy*` or `getAllBy*` query variant or not.
*/
const isGetByQuery: DetectionHelpers['isGetByQuery'] = (node) => {
return /^get(All)?By.+$/.test(node.name);
};
/**
* Determines whether a given node is `queryBy*` or `queryAllBy*` query variant or not.
*/
const isQueryByQuery: DetectionHelpers['isQueryByQuery'] = (node) => {
return /^query(All)?By.+$/.test(node.name);
};
/**
* Determines whether a given node is `findBy*` or `findAllBy*` query variant or not.
*/
const isFindByQuery: DetectionHelpers['isFindByQuery'] = (node) => {
return /^find(All)?By.+$/.test(node.name);
};
/**
* Determines whether a given node is sync query or not.
*/
const isSyncQuery: DetectionHelpers['isSyncQuery'] = (node) => {
return isGetByQuery(node) || isQueryByQuery(node);
};
/**
* Determines whether a given node is async query or not.
*/
const isAsyncQuery: DetectionHelpers['isAsyncQuery'] = (node) => {
return isFindByQuery(node);
};
const isCustomQuery: DetectionHelpers['isCustomQuery'] = (node) => {
return (
(isSyncQuery(node) || isAsyncQuery(node)) &&
!ALL_QUERIES_COMBINATIONS.includes(node.name)
);
};
/**
* Determines whether a given node is async util or not.
*/
const isAsyncUtil: DetectionHelpers['isAsyncUtil'] = (node) => {
return ASYNC_UTILS.includes(node.name);
};
/**
* Determines whether a given node is fireEvent method or not
*/
const isFireEventMethod: DetectionHelpers['isFireEventMethod'] = (node) => {
const fireEventUtil = findImportedUtilSpecifier(FIRE_EVENT_NAME);
let fireEventUtilName: string | undefined;
if (fireEventUtil) {
fireEventUtilName = ASTUtils.isIdentifier(fireEventUtil)
? fireEventUtil.name
: fireEventUtil.local.name;
} else if (isAggressiveReportingEnabled()) {
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 MemberExpression node is a presence assert
*
* Presence asserts could have shape of:
* - expect(element).toBeInTheDocument()
* - expect(element).not.toBeNull()
*/
const isPresenceAssert: DetectionHelpers['isPresenceAssert'] = (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: DetectionHelpers['isAbsenceAssert'] = (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: DetectionHelpers['findImportedUtilSpecifier'] = (
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: DetectionHelpers['canReportErrors'] = () => {
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: DetectionHelpers['isNodeComingFromTestingLibrary'] = (
node: TSESTree.MemberExpression | TSESTree.Identifier
) => {
let identifierName: string | undefined;
if (ASTUtils.isIdentifier(node)) {
identifierName = node.name;
} else if (ASTUtils.isIdentifier(node.object)) {
identifierName = node.object.name;
}
if (!identifierName) {
return;
}
return !!findImportedUtilSpecifier(identifierName);
};
const helpers = {
getTestingLibraryImportNode,
getCustomModuleImportNode,
getTestingLibraryImportName,
getCustomModuleImportName,
isTestingLibraryImported,
isValidFilename,
isGetByQuery,
isQueryByQuery,
isFindByQuery,
isSyncQuery,
isAsyncQuery,
isCustomQuery,
isAsyncUtil,
isFireEventMethod,
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;
};
}