forked from testing-library/eslint-plugin-testing-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefer-find-by.ts
484 lines (427 loc) · 13.9 KB
/
prefer-find-by.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
import { TSESTree, ASTUtils, TSESLint } from '@typescript-eslint/utils';
import { createTestingLibraryRule } from '../create-testing-library-rule';
import {
isArrowFunctionExpression,
isCallExpression,
isMemberExpression,
isObjectExpression,
isObjectPattern,
isProperty,
} from '../node-utils';
import { getScope, getSourceCode } from '../utils';
export const RULE_NAME = 'prefer-find-by';
export type MessageIds = 'preferFindBy';
type Options = [];
export function getFindByQueryVariant(
queryMethod: string
): 'findAllBy' | 'findBy' {
return queryMethod.includes('All') ? 'findAllBy' : 'findBy';
}
function findRenderDefinitionDeclaration(
scope: TSESLint.Scope.Scope | null,
query: string
): TSESTree.Identifier | null {
if (!scope) {
return null;
}
const variable = scope.variables.find(
(v: TSESLint.Scope.Variable) => v.name === query
);
if (variable) {
return (
variable.defs
.map(({ name }) => name)
.filter(ASTUtils.isIdentifier)
.find(({ name }) => name === query) ?? null
);
}
return findRenderDefinitionDeclaration(scope.upper, query);
}
export default createTestingLibraryRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description:
'Suggest using `find(All)By*` query instead of `waitFor` + `get(All)By*` to wait for elements',
recommendedConfig: {
dom: 'error',
angular: 'error',
react: 'error',
vue: 'error',
svelte: 'error',
marko: 'error',
},
},
messages: {
preferFindBy:
'Prefer `{{queryVariant}}{{queryMethod}}` query over using `waitFor` + `{{prevQuery}}`',
},
fixable: 'code',
schema: [],
},
defaultOptions: [],
create(context, _, helpers) {
const sourceCode = getSourceCode(context);
/**
* Reports the invalid usage of wait* plus getBy/QueryBy methods and automatically fixes the scenario
* @param node - The CallExpression node that contains the waitFor method
* @param replacementParams - Object with info for error message and autofix:
* @param replacementParams.queryVariant - The variant method used to query: findBy/findAllBy.
* @param replacementParams.prevQuery - The query originally used inside `waitFor`
* @param replacementParams.queryMethod - Suffix string to build the query method (the query-part that comes after the "By"): LabelText, Placeholder, Text, Role, Title, etc.
* @param replacementParams.fix - Function that applies the fix to correct the code
*/
function reportInvalidUsage(
node: TSESTree.CallExpression,
replacementParams: {
queryVariant: 'findAllBy' | 'findBy';
queryMethod: string;
prevQuery: string;
fix: TSESLint.ReportFixFunction;
}
) {
const { queryMethod, queryVariant, prevQuery, fix } = replacementParams;
context.report({
node,
messageId: 'preferFindBy',
data: {
queryVariant,
queryMethod,
prevQuery,
},
fix,
});
}
function getWrongQueryNameInAssertion(
node: TSESTree.ArrowFunctionExpression
) {
if (
!isCallExpression(node.body) ||
!isMemberExpression(node.body.callee)
) {
return null;
}
// expect(getByText).toBeInTheDocument() shape
if (
isCallExpression(node.body.callee.object) &&
isCallExpression(node.body.callee.object.arguments[0]) &&
ASTUtils.isIdentifier(node.body.callee.object.arguments[0].callee)
) {
return node.body.callee.object.arguments[0].callee;
}
if (!ASTUtils.isIdentifier(node.body.callee.property)) {
return null;
}
// expect(screen.getByText).toBeInTheDocument() shape
if (
isCallExpression(node.body.callee.object) &&
isCallExpression(node.body.callee.object.arguments[0]) &&
isMemberExpression(node.body.callee.object.arguments[0].callee) &&
ASTUtils.isIdentifier(
node.body.callee.object.arguments[0].callee.property
)
) {
return node.body.callee.object.arguments[0].callee.property;
}
// expect(screen.getByText).not shape
if (
isMemberExpression(node.body.callee.object) &&
isCallExpression(node.body.callee.object.object) &&
isCallExpression(node.body.callee.object.object.arguments[0]) &&
isMemberExpression(
node.body.callee.object.object.arguments[0].callee
) &&
ASTUtils.isIdentifier(
node.body.callee.object.object.arguments[0].callee.property
)
) {
return node.body.callee.object.object.arguments[0].callee.property;
}
// expect(getByText).not shape
if (
isMemberExpression(node.body.callee.object) &&
isCallExpression(node.body.callee.object.object) &&
isCallExpression(node.body.callee.object.object.arguments[0]) &&
ASTUtils.isIdentifier(
node.body.callee.object.object.arguments[0].callee
)
) {
return node.body.callee.object.object.arguments[0].callee;
}
return node.body.callee.property;
}
function getWrongQueryName(node: TSESTree.ArrowFunctionExpression) {
if (!isCallExpression(node.body)) {
return null;
}
// expect(() => getByText) and expect(() => screen.getByText) shape
if (
ASTUtils.isIdentifier(node.body.callee) &&
helpers.isSyncQuery(node.body.callee)
) {
return node.body.callee;
}
return getWrongQueryNameInAssertion(node);
}
function getCaller(node: TSESTree.ArrowFunctionExpression) {
if (
!isCallExpression(node.body) ||
!isMemberExpression(node.body.callee)
) {
return null;
}
if (ASTUtils.isIdentifier(node.body.callee.object)) {
// () => screen.getByText
return node.body.callee.object.name;
}
if (
// expect()
isCallExpression(node.body.callee.object) &&
ASTUtils.isIdentifier(node.body.callee.object.callee) &&
isCallExpression(node.body.callee.object.arguments[0]) &&
isMemberExpression(node.body.callee.object.arguments[0].callee) &&
ASTUtils.isIdentifier(
node.body.callee.object.arguments[0].callee.object
)
) {
return node.body.callee.object.arguments[0].callee.object.name;
}
if (
// expect().not
isMemberExpression(node.body.callee.object) &&
isCallExpression(node.body.callee.object.object) &&
isCallExpression(node.body.callee.object.object.arguments[0]) &&
isMemberExpression(
node.body.callee.object.object.arguments[0].callee
) &&
ASTUtils.isIdentifier(
node.body.callee.object.object.arguments[0].callee.object
)
) {
return node.body.callee.object.object.arguments[0].callee.object.name;
}
return null;
}
function isSyncQuery(node: TSESTree.ArrowFunctionExpression) {
if (!isCallExpression(node.body)) {
return false;
}
const isQuery =
ASTUtils.isIdentifier(node.body.callee) &&
helpers.isSyncQuery(node.body.callee);
const isWrappedInPresenceAssert =
isMemberExpression(node.body.callee) &&
isCallExpression(node.body.callee.object) &&
isCallExpression(node.body.callee.object.arguments[0]) &&
ASTUtils.isIdentifier(node.body.callee.object.arguments[0].callee) &&
helpers.isSyncQuery(node.body.callee.object.arguments[0].callee) &&
helpers.isPresenceAssert(node.body.callee);
const isWrappedInNegatedPresenceAssert =
isMemberExpression(node.body.callee) &&
isMemberExpression(node.body.callee.object) &&
isCallExpression(node.body.callee.object.object) &&
isCallExpression(node.body.callee.object.object.arguments[0]) &&
ASTUtils.isIdentifier(
node.body.callee.object.object.arguments[0].callee
) &&
helpers.isSyncQuery(
node.body.callee.object.object.arguments[0].callee
) &&
helpers.isPresenceAssert(node.body.callee.object);
return (
isQuery || isWrappedInPresenceAssert || isWrappedInNegatedPresenceAssert
);
}
function isScreenSyncQuery(node: TSESTree.ArrowFunctionExpression) {
if (!isArrowFunctionExpression(node) || !isCallExpression(node.body)) {
return false;
}
if (
!isMemberExpression(node.body.callee) ||
!ASTUtils.isIdentifier(node.body.callee.property)
) {
return false;
}
if (
!ASTUtils.isIdentifier(node.body.callee.object) &&
!isCallExpression(node.body.callee.object) &&
!isMemberExpression(node.body.callee.object)
) {
return false;
}
const isWrappedInPresenceAssert =
helpers.isPresenceAssert(node.body.callee) &&
isCallExpression(node.body.callee.object) &&
isCallExpression(node.body.callee.object.arguments[0]) &&
isMemberExpression(node.body.callee.object.arguments[0].callee) &&
ASTUtils.isIdentifier(
node.body.callee.object.arguments[0].callee.object
);
const isWrappedInNegatedPresenceAssert =
isMemberExpression(node.body.callee.object) &&
helpers.isPresenceAssert(node.body.callee.object) &&
isCallExpression(node.body.callee.object.object) &&
isCallExpression(node.body.callee.object.object.arguments[0]) &&
isMemberExpression(node.body.callee.object.object.arguments[0].callee);
return (
helpers.isSyncQuery(node.body.callee.property) ||
isWrappedInPresenceAssert ||
isWrappedInNegatedPresenceAssert
);
}
function getQueryArguments(node: TSESTree.CallExpression) {
if (
isMemberExpression(node.callee) &&
isCallExpression(node.callee.object) &&
isCallExpression(node.callee.object.arguments[0])
) {
return node.callee.object.arguments[0].arguments;
}
if (
isMemberExpression(node.callee) &&
isMemberExpression(node.callee.object) &&
isCallExpression(node.callee.object.object) &&
isCallExpression(node.callee.object.object.arguments[0])
) {
return node.callee.object.object.arguments[0].arguments;
}
return node.arguments;
}
return {
'AwaitExpression > CallExpression'(node: TSESTree.CallExpression) {
if (
!ASTUtils.isIdentifier(node.callee) ||
!helpers.isAsyncUtil(node.callee, ['waitFor'])
) {
return;
}
// ensure the only argument is an arrow function expression - if the arrow function is a block
// we skip it
const argument = node.arguments[0];
if (
!isArrowFunctionExpression(argument) ||
!isCallExpression(argument.body)
) {
return;
}
// ensure here it's one of the sync methods that we are calling
if (isScreenSyncQuery(argument)) {
const caller = getCaller(argument);
if (!caller) {
return;
}
// shape of () => screen.getByText
const fullQueryMethodNode = getWrongQueryName(argument);
if (!fullQueryMethodNode) {
return;
}
const fullQueryMethod = fullQueryMethodNode.name;
// if there is a second argument to AwaitExpression, it is the options
const waitOptions = node.arguments[1];
let waitOptionsSourceCode = '';
if (isObjectExpression(waitOptions)) {
waitOptionsSourceCode = `, ${sourceCode.getText(waitOptions)}`;
}
const queryVariant = getFindByQueryVariant(fullQueryMethod);
const callArguments = getQueryArguments(argument.body);
const queryMethod = fullQueryMethod.split('By')[1];
if (!queryMethod) {
return;
}
reportInvalidUsage(node, {
queryMethod,
queryVariant,
prevQuery: fullQueryMethod,
fix(fixer) {
const property = (
(argument.body as TSESTree.CallExpression)
.callee as TSESTree.MemberExpression
).property;
if (helpers.isCustomQuery(property as TSESTree.Identifier)) {
return null;
}
const newCode = `${caller}.${queryVariant}${queryMethod}(${callArguments
.map((callArgNode) => sourceCode.getText(callArgNode))
.join(', ')}${waitOptionsSourceCode})`;
return fixer.replaceText(node, newCode);
},
});
return;
}
if (!isSyncQuery(argument)) {
return;
}
// shape of () => getByText
const fullQueryMethodNode = getWrongQueryName(argument);
if (!fullQueryMethodNode) {
return;
}
const fullQueryMethod = fullQueryMethodNode.name;
const queryMethod = fullQueryMethod.split('By')[1];
const queryVariant = getFindByQueryVariant(fullQueryMethod);
const callArguments = getQueryArguments(argument.body);
reportInvalidUsage(node, {
queryMethod,
queryVariant,
prevQuery: fullQueryMethod,
fix(fixer) {
// we know from above callee is an Identifier
if (
helpers.isCustomQuery(
(argument.body as TSESTree.CallExpression)
.callee as TSESTree.Identifier
)
) {
return null;
}
const findByMethod = `${queryVariant}${queryMethod}`;
const allFixes: TSESLint.RuleFix[] = [];
// this updates waitFor with findBy*
const newCode = `${findByMethod}(${callArguments
.map((callArgNode) => sourceCode.getText(callArgNode))
.join(', ')})`;
allFixes.push(fixer.replaceText(node, newCode));
// this adds the findBy* declaration - adding it to the list of destructured variables { findBy* } = render()
const definition = findRenderDefinitionDeclaration(
getScope(context, fullQueryMethodNode),
fullQueryMethod
);
// I think it should always find it, otherwise code should not be valid (it'd be using undeclared variables)
if (!definition) {
return allFixes;
}
// check the declaration is part of a destructuring
if (
definition.parent &&
isObjectPattern(definition.parent.parent)
) {
const allVariableDeclarations = definition.parent.parent;
// verify if the findBy* method was already declared
if (
allVariableDeclarations.properties.some(
(p) =>
isProperty(p) &&
ASTUtils.isIdentifier(p.key) &&
p.key.name === findByMethod
)
) {
return allFixes;
}
// the last character of a destructuring is always a "}", so we should replace it with the findBy* declaration
const textDestructuring = sourceCode.getText(
allVariableDeclarations
);
const text = textDestructuring.replace(
/(\s*})$/,
`, ${findByMethod}$1`
);
allFixes.push(fixer.replaceText(allVariableDeclarations, text));
}
return allFixes;
},
});
},
};
},
});