/
no-if.ts
88 lines (80 loc) · 2.04 KB
/
no-if.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
import { TestCaseName, createRule, getNodeName, isTestCase } from './tsUtils';
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
const testCaseNames = new Set<string | null>([
...Object.keys(TestCaseName),
'it.only',
'it.skip',
'test.only',
'test.skip',
]);
const isTestArrowFunction = (node: TSESTree.ArrowFunctionExpression) =>
node.parent !== undefined &&
node.parent.type === AST_NODE_TYPES.CallExpression &&
testCaseNames.has(getNodeName(node.parent.callee));
export default createRule({
name: __filename,
meta: {
docs: {
description: 'Disallow conditional logic',
category: 'Best Practices',
recommended: false,
},
messages: {
noIf: 'Tests should not contain if statements.',
noConditional: 'Tests should not contain conditional statements.',
},
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create(context) {
const stack: boolean[] = [];
function validate(
node: TSESTree.ConditionalExpression | TSESTree.IfStatement,
) {
const lastElementInStack = stack[stack.length - 1];
if (stack.length === 0 || lastElementInStack === false) {
return;
}
const messageId =
node.type === AST_NODE_TYPES.ConditionalExpression
? 'noConditional'
: 'noIf';
context.report({
messageId,
node,
});
}
return {
CallExpression(node) {
stack.push(isTestCase(node));
},
FunctionExpression() {
stack.push(false);
},
FunctionDeclaration() {
stack.push(false);
},
ArrowFunctionExpression(node) {
stack.push(isTestArrowFunction(node));
},
IfStatement: validate,
ConditionalExpression: validate,
'CallExpression:exit'() {
stack.pop();
},
'FunctionExpression:exit'() {
stack.pop();
},
'FunctionDeclaration:exit'() {
stack.pop();
},
'ArrowFunctionExpression:exit'() {
stack.pop();
},
};
},
});