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
75 lines (68 loc) · 2.08 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
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
import { TSESTree, ASTUtils } from '@typescript-eslint/utils';
import { createTestingLibraryRule } from '../create-testing-library-rule';
import { ALL_RETURNING_NODES } from '../utils';
export const RULE_NAME = 'no-node-access';
export type MessageIds = 'noNodeAccess';
export type Options = [{ allowContainerFirstChild: boolean }];
export default createTestingLibraryRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'problem',
docs: {
description: 'Disallow direct Node access',
recommendedConfig: {
dom: false,
angular: 'error',
react: 'error',
vue: 'error',
marko: 'error',
},
},
messages: {
noNodeAccess:
'Avoid direct Node access. Prefer using the methods from Testing Library.',
},
schema: [
{
type: 'object',
properties: {
allowContainerFirstChild: {
type: 'boolean',
},
},
},
],
},
defaultOptions: [
{
allowContainerFirstChild: false,
},
],
create(context, [{ allowContainerFirstChild = false }], helpers) {
function showErrorForNodeAccess(node: TSESTree.MemberExpression) {
// This rule is so aggressive that can cause tons of false positives outside test files when Aggressive Reporting
// is enabled. Because of that, this rule will skip this mechanism and report only if some Testing Library package
// or custom one (set in utils-module Shared Setting) is found.
if (!helpers.isTestingLibraryImported(true)) {
return;
}
if (
ASTUtils.isIdentifier(node.property) &&
ALL_RETURNING_NODES.includes(node.property.name)
) {
if (allowContainerFirstChild && node.property.name === 'firstChild') {
return;
}
context.report({
node,
loc: node.property.loc.start,
messageId: 'noNodeAccess',
});
}
}
return {
'ExpressionStatement MemberExpression': showErrorForNodeAccess,
'VariableDeclarator MemberExpression': showErrorForNodeAccess,
};
},
});