-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathprefer-presence-queries.ts
91 lines (80 loc) · 2.72 KB
/
prefer-presence-queries.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
import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import { getDocsUrl, ALL_QUERIES_METHODS, PRESENCE_MATCHERS, ABSENCE_MATCHERS } from '../utils';
import {
findClosestCallNode,
isMemberExpression,
isIdentifier,
} from '../node-utils';
export const RULE_NAME = 'prefer-presence-queries';
export type MessageIds = 'presenceQuery' | 'absenceQuery' | 'expectQueryBy';
type Options = [];
const QUERIES_REGEXP = new RegExp(
`^(get|query)(All)?(${ALL_QUERIES_METHODS.join('|')})$`
);
function isThrowingQuery(node: TSESTree.Identifier) {
return node.name.startsWith('get');
}
export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
name: RULE_NAME,
meta: {
docs: {
category: 'Best Practices',
description:
'Ensure appropriate get*/query* queries are used with their respective matchers',
recommended: 'error',
},
messages: {
presenceQuery:
'Use `getBy*` queries rather than `queryBy*` for checking element is present',
absenceQuery:
'Use `queryBy*` queries rather than `getBy*` for checking element is NOT present',
expectQueryBy:
'Use `getBy*` only when checking elements are present, otherwise use `queryBy*`',
},
schema: [],
type: 'suggestion',
fixable: null,
},
defaultOptions: [],
create(context) {
return {
[`CallExpression Identifier[name=${QUERIES_REGEXP}]`](
node: TSESTree.Identifier
) {
const expectCallNode = findClosestCallNode(node, 'expect');
if (expectCallNode && isMemberExpression(expectCallNode.parent)) {
const expectStatement = expectCallNode.parent;
const property = expectStatement.property as TSESTree.Identifier;
let matcher = property.name;
let isNegatedMatcher = false;
if (
matcher === 'not' &&
isMemberExpression(expectStatement.parent) &&
isIdentifier(expectStatement.parent.property)
) {
isNegatedMatcher = true;
matcher = expectStatement.parent.property.name;
}
const validMatchers = isThrowingQuery(node)
? PRESENCE_MATCHERS
: ABSENCE_MATCHERS;
const invalidMatchers = isThrowingQuery(node)
? ABSENCE_MATCHERS
: PRESENCE_MATCHERS;
const messageId = isThrowingQuery(node)
? 'absenceQuery'
: 'presenceQuery';
if (
(!isNegatedMatcher && invalidMatchers.includes(matcher)) ||
(isNegatedMatcher && validMatchers.includes(matcher))
) {
return context.report({
node,
messageId,
});
}
}
},
};
},
});