/
no-if.js
70 lines (62 loc) · 1.55 KB
/
no-if.js
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
import { getDocsUrl, isTestCase } from './util';
const isTestArrowFunction = node =>
node !== undefined &&
node.type === 'ArrowFunctionExpression' &&
isTestCase(node.parent);
export default {
meta: {
docs: {
description: 'Disallow conditional logic',
category: 'Best Practices',
recommended: false,
uri: getDocsUrl('jest/no-if'),
},
messages: {
noIf: 'Tests should not contain if statements.',
noConditional: 'Tests should not contain conditional statements.',
},
},
create(context) {
const stack = [];
function validate(node) {
const lastElementInStack = stack[stack.length - 1];
if (stack.length === 0 || lastElementInStack === false) {
return;
}
const messageId =
node.type === '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();
},
};
},
};