-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathdetect-testing-library-utils.ts
1136 lines (993 loc) · 34.3 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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ASTUtils, TSESLint, TSESTree } from '@typescript-eslint/utils';
import {
findClosestVariableDeclaratorNode,
findImportSpecifier,
getAssertNodeInfo,
getDeepestIdentifierNode,
getImportModuleName,
getPropertyIdentifierNode,
getReferenceNode,
hasImportMatch,
ImportModuleNode,
isCallExpression,
isImportDeclaration,
isImportDefaultSpecifier,
isImportSpecifier,
isLiteral,
isMemberExpression,
} from '../node-utils';
import {
ABSENCE_MATCHERS,
ALL_QUERIES_COMBINATIONS,
ASYNC_UTILS,
DEBUG_UTILS,
PRESENCE_MATCHERS,
} from '../utils';
const SETTING_OPTION_OFF = 'off';
export type TestingLibrarySettings = {
'testing-library/utils-module'?:
| typeof SETTING_OPTION_OFF
| (string & NonNullable<unknown>);
'testing-library/custom-renders'?: string[] | typeof SETTING_OPTION_OFF;
'testing-library/custom-queries'?: string[] | typeof SETTING_OPTION_OFF;
};
export type TestingLibraryContext<
TMessageIds extends string,
TOptions extends readonly unknown[],
> = Readonly<
TSESLint.RuleContext<TMessageIds, TOptions> & {
settings: TestingLibrarySettings;
}
>;
export type EnhancedRuleCreate<
TMessageIds extends string,
TOptions extends readonly unknown[],
> = (
context: TestingLibraryContext<TMessageIds, TOptions>,
optionsWithDefault: Readonly<TOptions>,
detectionHelpers: Readonly<DetectionHelpers>
) => TSESLint.RuleListener;
// Helpers methods
type GetTestingLibraryImportNodeFn = () => ImportModuleNode | null;
type GetTestingLibraryImportNodesFn = () => ImportModuleNode[];
type GetCustomModuleImportNodeFn = () => ImportModuleNode | null;
type GetTestingLibraryImportNameFn = () => string | undefined;
type GetCustomModuleImportNameFn = () => string | undefined;
type IsTestingLibraryImportedFn = (isStrict?: boolean) => 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 IsQueryFn = (node: TSESTree.Identifier) => boolean;
type IsCustomQueryFn = (node: TSESTree.Identifier) => boolean;
type IsBuiltInQueryFn = (node: TSESTree.Identifier) => boolean;
type IsAsyncUtilFn = (
node: TSESTree.Identifier,
validNames?: readonly (typeof ASYNC_UTILS)[number][]
) => boolean;
type IsFireEventMethodFn = (node: TSESTree.Identifier) => boolean;
type IsUserEventMethodFn = (node: TSESTree.Identifier) => boolean;
type IsRenderUtilFn = (node: TSESTree.Identifier) => boolean;
type IsCreateEventUtil = (
node: TSESTree.CallExpression | TSESTree.Identifier
) => boolean;
type IsRenderVariableDeclaratorFn = (
node: TSESTree.VariableDeclarator
) => boolean;
type IsDebugUtilFn = (
identifierNode: TSESTree.Identifier,
validNames?: ReadonlyArray<(typeof DEBUG_UTILS)[number]>
) => boolean;
type IsPresenceAssertFn = (node: TSESTree.MemberExpression) => boolean;
type IsMatchingAssertFn = (
node: TSESTree.MemberExpression,
matcherName: string
) => boolean;
type IsAbsenceAssertFn = (node: TSESTree.MemberExpression) => boolean;
type CanReportErrorsFn = () => boolean;
type FindImportedTestingLibraryUtilSpecifierFn = (
specifierName: string
) => TSESTree.Identifier | TSESTree.ImportClause | undefined;
type IsNodeComingFromTestingLibraryFn = (
node: TSESTree.Identifier | TSESTree.MemberExpression
) => boolean;
export interface DetectionHelpers {
getTestingLibraryImportNode: GetTestingLibraryImportNodeFn;
getAllTestingLibraryImportNodes: GetTestingLibraryImportNodesFn;
getCustomModuleImportNode: GetCustomModuleImportNodeFn;
getTestingLibraryImportName: GetTestingLibraryImportNameFn;
getCustomModuleImportName: GetCustomModuleImportNameFn;
isTestingLibraryImported: IsTestingLibraryImportedFn;
isTestingLibraryUtil: (node: TSESTree.Identifier) => boolean;
isGetQueryVariant: IsGetQueryVariantFn;
isQueryQueryVariant: IsQueryQueryVariantFn;
isFindQueryVariant: IsFindQueryVariantFn;
isSyncQuery: IsSyncQueryFn;
isAsyncQuery: IsAsyncQueryFn;
isQuery: IsQueryFn;
isCustomQuery: IsCustomQueryFn;
isBuiltInQuery: IsBuiltInQueryFn;
isAsyncUtil: IsAsyncUtilFn;
isFireEventUtil: (node: TSESTree.Identifier) => boolean;
isUserEventUtil: (node: TSESTree.Identifier) => boolean;
isFireEventMethod: IsFireEventMethodFn;
isUserEventMethod: IsUserEventMethodFn;
isRenderUtil: IsRenderUtilFn;
isCreateEventUtil: IsCreateEventUtil;
isRenderVariableDeclarator: IsRenderVariableDeclaratorFn;
isDebugUtil: IsDebugUtilFn;
isActUtil: (node: TSESTree.Identifier) => boolean;
isPresenceAssert: IsPresenceAssertFn;
isAbsenceAssert: IsAbsenceAssertFn;
isMatchingAssert: IsMatchingAssertFn;
canReportErrors: CanReportErrorsFn;
findImportedTestingLibraryUtilSpecifier: FindImportedTestingLibraryUtilSpecifierFn;
isNodeComingFromTestingLibrary: IsNodeComingFromTestingLibraryFn;
}
const USER_EVENT_PACKAGE = '@testing-library/user-event';
const REACT_DOM_TEST_UTILS_PACKAGE = 'react-dom/test-utils';
const FIRE_EVENT_NAME = 'fireEvent';
const CREATE_EVENT_NAME = 'createEvent';
const USER_EVENT_NAME = 'userEvent';
const RENDER_NAME = 'render';
export type DetectionOptions = {
/**
* If true, force `detectTestingLibraryUtils` to skip `canReportErrors`
* so it doesn't opt-out rule listener.
*
* Useful when some rule apply to files other than testing ones
* (e.g. `consistent-data-testid`)
*/
skipRuleReportingCheck: boolean;
};
/**
* Enhances a given rule `create` with helpers to detect Testing Library utils.
*/
export function detectTestingLibraryUtils<
TMessageIds extends string,
TOptions extends readonly unknown[],
>(
ruleCreate: EnhancedRuleCreate<TMessageIds, TOptions>,
{ skipRuleReportingCheck = false }: Partial<DetectionOptions> = {}
) {
return (
context: TestingLibraryContext<TMessageIds, TOptions>,
optionsWithDefault: Readonly<TOptions>
): TSESLint.RuleListener => {
const importedTestingLibraryNodes: ImportModuleNode[] = [];
let importedCustomModuleNode: ImportModuleNode | null = null;
let importedUserEventLibraryNode: ImportModuleNode | null = null;
let importedReactDomTestUtilsNode: ImportModuleNode | null = null;
// Init options based on shared ESLint settings
const customModuleSetting =
context.settings['testing-library/utils-module'];
const customRendersSetting =
context.settings['testing-library/custom-renders'];
const customQueriesSetting =
context.settings['testing-library/custom-queries'];
/**
* Small method to extract common checks to determine whether a node is
* related to Testing Library or not.
*
* To determine whether a node is a valid Testing Library util, there are
* two conditions to match:
* - it's named in a particular way (decided by given callback)
* - it's imported from valid Testing Library module (depends on aggressive
* reporting)
*/
function isPotentialTestingLibraryFunction(
node: TSESTree.Identifier | null | undefined,
isPotentialFunctionCallback: (
identifierNodeName: string,
originalNodeName?: string
) => boolean
): boolean {
if (!node) {
return false;
}
const referenceNode = getReferenceNode(node);
const referenceNodeIdentifier = getPropertyIdentifierNode(referenceNode);
if (!referenceNodeIdentifier) {
return false;
}
const importedUtilSpecifier = getTestingLibraryImportedUtilSpecifier(
referenceNodeIdentifier
);
const originalNodeName =
isImportSpecifier(importedUtilSpecifier) &&
ASTUtils.isIdentifier(importedUtilSpecifier.imported) &&
importedUtilSpecifier.local.name !== importedUtilSpecifier.imported.name
? importedUtilSpecifier.imported.name
: undefined;
if (!isPotentialFunctionCallback(node.name, originalNodeName)) {
return false;
}
if (isAggressiveModuleReportingEnabled()) {
return true;
}
return 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 = () => !customModuleSetting;
/**
* 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 = (): boolean => {
const isSwitchedOff = customRendersSetting === SETTING_OPTION_OFF;
const hasCustomOptions =
Array.isArray(customRendersSetting) && customRendersSetting.length > 0;
return !isSwitchedOff && !hasCustomOptions;
};
/**
* Determines whether Aggressive Reporting for queries is enabled or not.
*
* This Aggressive Reporting mechanism is considered as enabled when custom-queries setting is not set,
* so the plugin needs to report both built-in and custom queries.
* Otherwise, this Aggressive Reporting mechanism is opted-out in favour of reporting only built-in queries + those
* indicated in custom-queries setting.
*/
const isAggressiveQueryReportingEnabled = (): boolean => {
const isSwitchedOff = customQueriesSetting === SETTING_OPTION_OFF;
const hasCustomOptions =
Array.isArray(customQueriesSetting) && customQueriesSetting.length > 0;
return !isSwitchedOff && !hasCustomOptions;
};
const getCustomModule = (): string | undefined => {
if (
!isAggressiveModuleReportingEnabled() &&
customModuleSetting !== SETTING_OPTION_OFF
) {
return customModuleSetting;
}
return undefined;
};
const getCustomRenders = (): string[] => {
if (
!isAggressiveRenderReportingEnabled() &&
customRendersSetting !== SETTING_OPTION_OFF
) {
return customRendersSetting as string[];
}
return [];
};
const getCustomQueries = (): string[] => {
if (
!isAggressiveQueryReportingEnabled() &&
customQueriesSetting !== SETTING_OPTION_OFF
) {
return customQueriesSetting as string[];
}
return [];
};
// Helpers for Testing Library detection.
const getTestingLibraryImportNode: GetTestingLibraryImportNodeFn = () => {
return importedTestingLibraryNodes[0];
};
const getAllTestingLibraryImportNodes: GetTestingLibraryImportNodesFn =
() => {
return importedTestingLibraryNodes;
};
const getCustomModuleImportNode: GetCustomModuleImportNodeFn = () => {
return importedCustomModuleNode;
};
const getTestingLibraryImportName: GetTestingLibraryImportNameFn = () => {
return getImportModuleName(importedTestingLibraryNodes[0]);
};
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 = (
isStrict = false
) => {
const isSomeModuleImported =
importedTestingLibraryNodes.length !== 0 || !!importedCustomModuleNode;
return (
(!isStrict && isAggressiveModuleReportingEnabled()) ||
isSomeModuleImported
);
};
/**
* Determines whether a given node is a reportable query,
* either a built-in or a custom one.
*
* Depending on Aggressive Query Reporting setting, custom queries will be
* reportable or not.
*/
const isQuery: IsQueryFn = (node) => {
const hasQueryPattern = /^(get|query|find)(All)?By.+$/.test(node.name);
if (!hasQueryPattern) {
return false;
}
if (isAggressiveQueryReportingEnabled()) {
return true;
}
const customQueries = getCustomQueries();
const isBuiltInQuery = ALL_QUERIES_COMBINATIONS.includes(node.name);
const isReportableCustomQuery = customQueries.some((pattern) =>
new RegExp(pattern).test(node.name)
);
return isBuiltInQuery || isReportableCustomQuery;
};
/**
* Determines whether a given node is `get*` query variant or not.
*/
const isGetQueryVariant: IsGetQueryVariantFn = (node) => {
return isQuery(node) && node.name.startsWith('get');
};
/**
* Determines whether a given node is `query*` query variant or not.
*/
const isQueryQueryVariant: IsQueryQueryVariantFn = (node) => {
return isQuery(node) && node.name.startsWith('query');
};
/**
* Determines whether a given node is `find*` query variant or not.
*/
const isFindQueryVariant: IsFindQueryVariantFn = (node) => {
return isQuery(node) && node.name.startsWith('find');
};
/**
* 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 isQuery(node) && !ALL_QUERIES_COMBINATIONS.includes(node.name);
};
const isBuiltInQuery = (node: TSESTree.Identifier): boolean => {
return isQuery(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, validNames = ASYNC_UTILS) => {
return isPotentialTestingLibraryFunction(
node,
(identifierNodeName, originalNodeName) => {
return (
(validNames as string[]).includes(identifierNodeName) ||
(!!originalNodeName &&
(validNames as string[]).includes(originalNodeName))
);
}
);
};
/**
* Determines whether a given node is fireEvent util itself or not.
*
* Not to be confused with {@link isFireEventMethod}
*/
const isFireEventUtil = (node: TSESTree.Identifier): boolean => {
return isPotentialTestingLibraryFunction(
node,
(identifierNodeName, originalNodeName) => {
return [identifierNodeName, originalNodeName].includes('fireEvent');
}
);
};
/**
* Determines whether a given node is userEvent util itself or not.
*
* Not to be confused with {@link isUserEventMethod}
*/
const isUserEventUtil = (node: TSESTree.Identifier): boolean => {
const userEvent = findImportedUserEventSpecifier();
let userEventName: string | undefined;
if (userEvent) {
userEventName = userEvent.name;
} else if (isAggressiveModuleReportingEnabled()) {
userEventName = USER_EVENT_NAME;
}
if (!userEventName) {
return false;
}
return node.name === userEventName;
};
/**
* Determines whether a given node is fireEvent method or not
*/
// eslint-disable-next-line complexity
const isFireEventMethod: IsFireEventMethodFn = (node) => {
const fireEventUtil =
findImportedTestingLibraryUtilSpecifier(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 =
node.parent && isMemberExpression(node.parent)
? node.parent
: undefined;
const parentCallExpression: TSESTree.CallExpression | undefined =
node.parent && isCallExpression(node.parent) ? node.parent : undefined;
if (!parentMemberExpression && !parentCallExpression) {
return false;
}
// check fireEvent('method', node) usage
if (parentCallExpression) {
return [fireEventUtilName, FIRE_EVENT_NAME].includes(node.name);
}
// we know it's defined at this point, but TS seems to think it is not
// so here I'm enforcing it once in order to avoid using "!" operator every time
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const definedParentMemberExpression = parentMemberExpression!;
// check fireEvent.click() usage
const regularCall =
ASTUtils.isIdentifier(definedParentMemberExpression.object) &&
isCallExpression(definedParentMemberExpression.parent) &&
definedParentMemberExpression.object.name === fireEventUtilName &&
node.name !== FIRE_EVENT_NAME &&
node.name !== fireEventUtilName;
// check testingLibraryUtils.fireEvent.click() usage
const wildcardCall =
isMemberExpression(definedParentMemberExpression.object) &&
ASTUtils.isIdentifier(definedParentMemberExpression.object.object) &&
definedParentMemberExpression.object.object.name ===
fireEventUtilName &&
ASTUtils.isIdentifier(definedParentMemberExpression.object.property) &&
definedParentMemberExpression.object.property.name ===
FIRE_EVENT_NAME &&
node.name !== FIRE_EVENT_NAME &&
node.name !== fireEventUtilName;
// check testingLibraryUtils.fireEvent('click')
const wildcardCallWithCallExpression =
ASTUtils.isIdentifier(definedParentMemberExpression.object) &&
definedParentMemberExpression.object.name === fireEventUtilName &&
ASTUtils.isIdentifier(definedParentMemberExpression.property) &&
definedParentMemberExpression.property.name === FIRE_EVENT_NAME &&
!isMemberExpression(definedParentMemberExpression.parent) &&
node.name === FIRE_EVENT_NAME &&
node.name !== fireEventUtilName;
return regularCall || wildcardCall || wildcardCallWithCallExpression;
};
const isUserEventMethod: IsUserEventMethodFn = (node) => {
const userEvent = findImportedUserEventSpecifier();
let userEventName: string | undefined;
if (userEvent) {
userEventName = userEvent.name;
} else if (isAggressiveModuleReportingEnabled()) {
userEventName = USER_EVENT_NAME;
}
if (!userEventName) {
return false;
}
const parentMemberExpression: TSESTree.MemberExpression | undefined =
node.parent && isMemberExpression(node.parent)
? node.parent
: undefined;
if (!parentMemberExpression) {
return false;
}
// make sure that given node it's not userEvent object itself
if (
[userEventName, USER_EVENT_NAME].includes(node.name) ||
(ASTUtils.isIdentifier(parentMemberExpression.object) &&
parentMemberExpression.object.name === node.name)
) {
return false;
}
// check userEvent.click() usage
return (
ASTUtils.isIdentifier(parentMemberExpression.object) &&
parentMemberExpression.object.name === userEventName
);
};
/**
* 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) =>
isPotentialTestingLibraryFunction(
node,
(identifierNodeName, originalNodeName) => {
if (isAggressiveRenderReportingEnabled()) {
return identifierNodeName.toLowerCase().includes(RENDER_NAME);
}
return [RENDER_NAME, ...getCustomRenders()].some(
(validRenderName) =>
validRenderName === identifierNodeName ||
(Boolean(originalNodeName) &&
validRenderName === originalNodeName)
);
}
);
const isCreateEventUtil: IsCreateEventUtil = (node) => {
const isCreateEventCallback = (
identifierNodeName: string,
originalNodeName?: string
) => [identifierNodeName, originalNodeName].includes(CREATE_EVENT_NAME);
if (
isCallExpression(node) &&
isMemberExpression(node.callee) &&
ASTUtils.isIdentifier(node.callee.object)
) {
return isPotentialTestingLibraryFunction(
node.callee.object,
isCreateEventCallback
);
}
if (
isCallExpression(node) &&
isMemberExpression(node.callee) &&
isMemberExpression(node.callee.object) &&
ASTUtils.isIdentifier(node.callee.object.property)
) {
return isPotentialTestingLibraryFunction(
node.callee.object.property,
isCreateEventCallback
);
}
const identifier = getDeepestIdentifierNode(node);
return isPotentialTestingLibraryFunction(
identifier,
isCreateEventCallback
);
};
const isRenderVariableDeclarator: IsRenderVariableDeclaratorFn = (node) => {
if (!node.init) {
return false;
}
const initIdentifierNode = getDeepestIdentifierNode(node.init);
if (!initIdentifierNode) {
return false;
}
return isRenderUtil(initIdentifierNode);
};
const isDebugUtil: IsDebugUtilFn = (
identifierNode,
validNames = DEBUG_UTILS
) => {
const isBuiltInConsole =
isMemberExpression(identifierNode.parent) &&
ASTUtils.isIdentifier(identifierNode.parent.object) &&
identifierNode.parent.object.name === 'console';
return (
!isBuiltInConsole &&
isPotentialTestingLibraryFunction(
identifierNode,
(identifierNodeName, originalNodeName) => {
return (
(validNames as string[]).includes(identifierNodeName) ||
(!!originalNodeName &&
(validNames as string[]).includes(originalNodeName))
);
}
)
);
};
/**
* Determines whether a given node is some reportable `act` util.
*
* An `act` is reportable if some of these conditions is met:
* - it's related to Testing Library module (this depends on Aggressive Reporting)
* - it's related to React DOM Test Utils
*/
const isActUtil = (node: TSESTree.Identifier): boolean => {
const isTestingLibraryAct = isPotentialTestingLibraryFunction(
node,
(identifierNodeName, originalNodeName) => {
return [identifierNodeName, originalNodeName]
.filter(Boolean)
.includes('act');
}
);
const isReactDomTestUtilsAct = (() => {
if (!importedReactDomTestUtilsNode) {
return false;
}
const referenceNode = getReferenceNode(node);
const referenceNodeIdentifier =
getPropertyIdentifierNode(referenceNode);
if (!referenceNodeIdentifier) {
return false;
}
const importedUtilSpecifier = findImportSpecifier(
node.name,
importedReactDomTestUtilsNode
);
if (!importedUtilSpecifier) {
return false;
}
const importDeclaration = (() => {
if (isImportDeclaration(importedUtilSpecifier.parent)) {
return importedUtilSpecifier.parent;
}
const variableDeclarator = findClosestVariableDeclaratorNode(
importedUtilSpecifier
);
if (isCallExpression(variableDeclarator?.init)) {
return variableDeclarator?.init;
}
return undefined;
})();
if (!importDeclaration) {
return false;
}
const importDeclarationName = getImportModuleName(importDeclaration);
if (!importDeclarationName) {
return false;
}
if (importDeclarationName !== REACT_DOM_TEST_UTILS_PACKAGE) {
return false;
}
return hasImportMatch(
importedUtilSpecifier,
referenceNodeIdentifier.name
);
})();
return isTestingLibraryAct || isReactDomTestUtilsAct;
};
const isTestingLibraryUtil = (node: TSESTree.Identifier): boolean => {
return (
isAsyncUtil(node) ||
isQuery(node) ||
isRenderUtil(node) ||
isFireEventMethod(node) ||
isUserEventMethod(node) ||
isActUtil(node) ||
isCreateEventUtil(node)
);
};
/**
* 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);
};
const isMatchingAssert: IsMatchingAssertFn = (node, matcherName) => {
const { matcher } = getAssertNodeInfo(node);
if (!matcher) {
return false;
}
return matcher === matcherName;
};
/**
* Finds the import util specifier related to Testing Library for a given name.
*/
const findImportedTestingLibraryUtilSpecifier: FindImportedTestingLibraryUtilSpecifierFn =
(
specifierName
): TSESTree.Identifier | TSESTree.ImportClause | undefined => {
const node =
getCustomModuleImportNode() ?? getTestingLibraryImportNode();
if (!node) {
return undefined;
}
return findImportSpecifier(specifierName, node);
};
const findImportedUserEventSpecifier: () => TSESTree.Identifier | null =
() => {
if (!importedUserEventLibraryNode) {
return null;
}
if (isImportDeclaration(importedUserEventLibraryNode)) {
const userEventIdentifier =
importedUserEventLibraryNode.specifiers.find((specifier) =>
isImportDefaultSpecifier(specifier)
);
if (userEventIdentifier) {
return userEventIdentifier.local;
}
} else {
if (
!ASTUtils.isVariableDeclarator(importedUserEventLibraryNode.parent)
) {
return null;
}
const requireNode = importedUserEventLibraryNode.parent;
if (!ASTUtils.isIdentifier(requireNode.id)) {
return null;
}
return requireNode.id;
}
return null;
};
const getTestingLibraryImportedUtilSpecifier = (
node: TSESTree.Identifier | TSESTree.MemberExpression
): TSESTree.Identifier | TSESTree.ImportClause | undefined => {
const identifierName: string | undefined =
getPropertyIdentifierNode(node)?.name;
if (!identifierName) {
return undefined;
}
return findImportedTestingLibraryUtilSpecifier(identifierName);
};
/**
* Determines if file inspected meets all conditions to be reported by rules or not.
*/
const canReportErrors: CanReportErrorsFn = () => {
return skipRuleReportingCheck || isTestingLibraryImported();
};
/**
* Determines whether a node is imported from a valid Testing Library module
*
* This method will try to find any import matching the given node name,
* and also make sure the name is a valid match in case it's been renamed.
*/
const isNodeComingFromTestingLibrary: IsNodeComingFromTestingLibraryFn = (
node
) => {
const importNode = getTestingLibraryImportedUtilSpecifier(node);
if (!importNode) {
return false;
}
const referenceNode = getReferenceNode(node);
const referenceNodeIdentifier = getPropertyIdentifierNode(referenceNode);
if (!referenceNodeIdentifier) {
return false;
}
const importDeclaration = (() => {
if (isImportDeclaration(importNode.parent)) {
return importNode.parent;
}
const variableDeclarator =
findClosestVariableDeclaratorNode(importNode);
if (isCallExpression(variableDeclarator?.init)) {
return variableDeclarator?.init;
}
return undefined;
})();
if (!importDeclaration) {
return false;
}
const importDeclarationName = getImportModuleName(importDeclaration);
if (!importDeclarationName) {
return false;
}
const identifierName: string | undefined =
getPropertyIdentifierNode(node)?.name;
if (!identifierName) {
return false;
}
const hasImportElementMatch = hasImportMatch(importNode, identifierName);
const hasImportModuleMatch =
/testing-library/g.test(importDeclarationName) ||
(typeof customModuleSetting === 'string' &&
importDeclarationName.endsWith(customModuleSetting));
return hasImportElementMatch && hasImportModuleMatch;
};
const helpers: DetectionHelpers = {
getTestingLibraryImportNode,
getAllTestingLibraryImportNodes,
getCustomModuleImportNode,
getTestingLibraryImportName,
getCustomModuleImportName,
isTestingLibraryImported,
isTestingLibraryUtil,
isGetQueryVariant,
isQueryQueryVariant,
isFindQueryVariant,
isSyncQuery,
isAsyncQuery,
isQuery,
isCustomQuery,
isBuiltInQuery,
isAsyncUtil,
isFireEventUtil,
isUserEventUtil,
isFireEventMethod,
isUserEventMethod,
isRenderUtil,
isCreateEventUtil,
isRenderVariableDeclarator,
isDebugUtil,
isActUtil,
isPresenceAssert,
isMatchingAssert,
isAbsenceAssert,
canReportErrors,
findImportedTestingLibraryUtilSpecifier,
isNodeComingFromTestingLibrary,