forked from jest-community/eslint-plugin-jest
/
max-expects.ts
89 lines (80 loc) · 2.04 KB
/
max-expects.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
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import {
FunctionExpression,
createRule,
isExpectCall,
isTypeOfJestFnCall,
} from './utils';
export default createRule({
name: __filename,
meta: {
docs: {
category: 'Best Practices',
description: 'Enforces a maximum assertion calls in a test body',
recommended: false,
},
messages: {
exceededMaxAssertion:
'Too many assertion calls ({{ count }}). Maximum allowed is {{ max }}.',
},
type: 'suggestion',
schema: [
{
type: 'object',
properties: {
max: {
type: 'integer',
minimum: 0,
},
},
additionalProperties: false,
},
],
},
defaultOptions: [{ max: 5 }],
create(context, [{ max }]) {
let count = 0;
const onFunctionExpressionEnter = (node: FunctionExpression) => {
if (!node?.parent) {
return;
}
const isTestFn =
node.parent.type !== AST_NODE_TYPES.CallExpression ||
isTypeOfJestFnCall(node.parent, context, ['test']);
if (isTestFn) {
count = 0;
return;
}
};
const onFunctionExpressionExit = (node: FunctionExpression) => {
if (!node?.parent) {
return;
}
const isTestFn =
node.parent.type !== AST_NODE_TYPES.CallExpression ||
isTypeOfJestFnCall(node.parent, context, ['test']);
if (isTestFn) {
count = count - 1;
return;
}
};
return {
FunctionExpression: onFunctionExpressionEnter,
'FunctionExpression:exit': onFunctionExpressionExit,
ArrowFunctionExpression: onFunctionExpressionEnter,
'ArrowFunctionExpression:exit': onFunctionExpressionExit,
CallExpression(node) {
if (isExpectCall(node)) {
count += 1;
}
if (count > max && node.parent) {
context.report({
node: node.parent,
messageId: 'exceededMaxAssertion',
data: { count, max },
});
}
},
};
},
});