-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathprefer-find-by.ts
223 lines (208 loc) · 7.46 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
import { TSESTree, ASTUtils } from '@typescript-eslint/experimental-utils';
import {
ReportFixFunction,
RuleFix,
Scope,
} from '@typescript-eslint/experimental-utils/dist/ts-eslint';
import {
isArrowFunctionExpression,
isCallExpression,
isMemberExpression,
isObjectPattern,
isProperty,
} from '../node-utils';
import { createTestingLibraryRule } from '../create-testing-library-rule';
export const RULE_NAME = 'prefer-find-by';
export type MessageIds = 'preferFindBy';
type Options = [];
export const WAIT_METHODS = ['waitFor', 'waitForElement', 'wait'];
export function getFindByQueryVariant(
queryMethod: string
): 'findAllBy' | 'findBy' {
return queryMethod.includes('All') ? 'findAllBy' : 'findBy';
}
function findRenderDefinitionDeclaration(
scope: Scope.Scope | null,
query: string
): TSESTree.Identifier | null {
if (!scope) {
return null;
}
const variable = scope.variables.find(
(v: Scope.Variable) => v.name === query
);
if (variable) {
return variable.defs
.map(({ name }) => name)
.filter(ASTUtils.isIdentifier)
.find(({ name }) => name === query);
}
return findRenderDefinitionDeclaration(scope.upper, query);
}
export default createTestingLibraryRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description:
'Suggest using find* instead of waitFor to wait for elements',
category: 'Best Practices',
recommended: 'warn',
},
messages: {
preferFindBy:
'Prefer {{queryVariant}}{{queryMethod}} method over using await {{fullQuery}}',
},
fixable: 'code',
schema: [],
},
defaultOptions: [],
create(context, _, helpers) {
const sourceCode = context.getSourceCode();
/**
* Reports the invalid usage of wait* plus getBy/QueryBy methods and automatically fixes the scenario
* @param {TSESTree.CallExpression} node - The CallExpresion node that contains the wait* method
* @param {'findBy' | 'findAllBy'} replacementParams.queryVariant - The variant method used to query: findBy/findByAll.
* @param {string} replacementParams.queryMethod - Suffix string to build the query method (the query-part that comes after the "By"): LabelText, Placeholder, Text, Role, Title, etc.
* @param {ReportFixFunction} replacementParams.fix - Function that applies the fix to correct the code
*/
function reportInvalidUsage(
node: TSESTree.CallExpression,
{
queryVariant,
queryMethod,
fix,
}: {
queryVariant: 'findBy' | 'findAllBy';
queryMethod: string;
fix: ReportFixFunction;
}
) {
context.report({
node,
messageId: 'preferFindBy',
data: {
queryVariant,
queryMethod,
fullQuery: sourceCode.getText(node),
},
fix,
});
}
return {
'AwaitExpression > CallExpression'(node: TSESTree.CallExpression) {
if (
!ASTUtils.isIdentifier(node.callee) ||
!WAIT_METHODS.includes(node.callee.name)
) {
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)) {
return;
}
if (!isCallExpression(argument.body)) {
return;
}
// ensure here it's one of the sync methods that we are calling
if (
isMemberExpression(argument.body.callee) &&
ASTUtils.isIdentifier(argument.body.callee.property) &&
ASTUtils.isIdentifier(argument.body.callee.object) &&
helpers.isSyncQuery(argument.body.callee.property)
) {
// shape of () => screen.getByText
const fullQueryMethod = argument.body.callee.property.name;
const caller = argument.body.callee.object.name;
const queryVariant = getFindByQueryVariant(fullQueryMethod);
const callArguments = argument.body.arguments;
const queryMethod = fullQueryMethod.split('By')[1];
reportInvalidUsage(node, {
queryMethod,
queryVariant,
fix(fixer) {
const property = ((argument.body as TSESTree.CallExpression)
.callee as TSESTree.MemberExpression).property;
if (helpers.isCustomQuery(property as TSESTree.Identifier)) {
return;
}
const newCode = `${caller}.${queryVariant}${queryMethod}(${callArguments
.map((node) => sourceCode.getText(node))
.join(', ')})`;
return fixer.replaceText(node, newCode);
},
});
return;
}
if (
!ASTUtils.isIdentifier(argument.body.callee) ||
!helpers.isSyncQuery(argument.body.callee)
) {
return;
}
// shape of () => getByText
const fullQueryMethod = argument.body.callee.name;
const queryMethod = fullQueryMethod.split('By')[1];
const queryVariant = getFindByQueryVariant(fullQueryMethod);
const callArguments = argument.body.arguments;
reportInvalidUsage(node, {
queryMethod,
queryVariant,
fix(fixer) {
// we know from above callee is an Identifier
if (
helpers.isCustomQuery(
(argument.body as TSESTree.CallExpression)
.callee as TSESTree.Identifier
)
) {
return;
}
const findByMethod = `${queryVariant}${queryMethod}`;
const allFixes: RuleFix[] = [];
// this updates waitFor with findBy*
const newCode = `${findByMethod}(${callArguments
.map((node) => sourceCode.getText(node))
.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(
context.getScope(),
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 (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.substring(0, textDestructuring.length - 2) +
`, ${findByMethod} }`;
allFixes.push(fixer.replaceText(allVariableDeclarations, text));
}
return allFixes;
},
});
},
};
},
});