-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathprefer-find-by.ts
152 lines (136 loc) · 6.34 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
import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import { ReportFixFunction, Scope, RuleFix } from '@typescript-eslint/experimental-utils/dist/ts-eslint'
import {
isIdentifier,
isCallExpression,
isMemberExpression,
isArrowFunctionExpression,
isObjectPattern,
isProperty,
} from '../node-utils';
import { getDocsUrl, SYNC_QUERIES_COMBINATIONS } from '../utils';
export const RULE_NAME = 'prefer-find-by';
type Options = [];
export type MessageIds = 'preferFindBy';
export const WAIT_METHODS = ['waitFor', 'waitForElement', 'wait']
export default ESLintUtils.RuleCreator(getDocsUrl)<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) {
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 (!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) && isIdentifier(argument.body.callee.property) && isIdentifier(argument.body.callee.object) && SYNC_QUERIES_COMBINATIONS.includes(argument.body.callee.property.name)) {
// 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 newCode = `${caller}.${queryVariant}${queryMethod}(${callArguments.map((node) => sourceCode.getText(node)).join(', ')})`
return fixer.replaceText(node, newCode)
}
})
return
}
if (isIdentifier(argument.body.callee) && SYNC_QUERIES_COMBINATIONS.includes(argument.body.callee.name)) {
// 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) {
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) && 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
}
})
return
}
}
}
}
})
export function getFindByQueryVariant(queryMethod: string) {
return queryMethod.includes('All') ? 'findAllBy' : 'findBy'
}
function findRenderDefinitionDeclaration(scope: Scope.Scope | null, query: string): TSESTree.Identifier | null {
if (!scope) {
return null
}
let variable = scope.variables.find((v: Scope.Variable) => v.name === query)
if (variable) {
const def = variable.defs.find(({ name }) => name.name === query)
return def.name
}
return findRenderDefinitionDeclaration(scope.upper, query)
}