forked from testing-library/eslint-plugin-testing-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathno-node-access.ts
49 lines (43 loc) · 1.43 KB
/
no-node-access.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
import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import { getDocsUrl, ALL_RETURNING_NODES } from '../utils';
import { isIdentifier } from '../node-utils';
export const RULE_NAME = 'no-node-access';
export default ESLintUtils.RuleCreator(getDocsUrl)({
name: RULE_NAME,
meta: {
type: 'problem',
docs: {
description: 'Disallow direct Node access',
category: 'Best Practices',
recommended: 'error',
},
messages: {
noNodeAccess:
'Avoid direct Node access. Prefer using the methods from Testing Library.',
},
fixable: null,
schema: [],
},
defaultOptions: [],
create(context) {
let isImportingTestingLibrary = false;
function checkTestingEnvironment(node: TSESTree.ImportDeclaration) {
isImportingTestingLibrary = /testing-library/g.test(node.source.value as string);
}
function showErrorForNodeAccess(node: TSESTree.MemberExpression) {
isIdentifier(node.property) &&
ALL_RETURNING_NODES.includes(node.property.name) &&
isImportingTestingLibrary &&
context.report({
node: node,
loc: node.property.loc.start,
messageId: 'noNodeAccess',
});
}
return {
['ImportDeclaration']: checkTestingEnvironment,
['ExpressionStatement MemberExpression']: showErrorForNodeAccess,
['VariableDeclarator MemberExpression']: showErrorForNodeAccess,
};
},
});