/
no-nested-tests.js
87 lines (76 loc) · 2.7 KB
/
no-nested-tests.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'use strict';
/* eslint "complexity": [ "error", 5 ] */
const createAstUtils = require('../util/ast');
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Disallow tests to be nested within other tests',
url: 'https://github.com/lo1tuma/eslint-plugin-mocha/blob/main/docs/rules/no-nested-tests.md'
},
schema: []
},
create(context) {
const astUtils = createAstUtils(context.settings);
let testNestingLevel = 0;
let hookCallNestingLevel = 0;
const isTestCase = astUtils.buildIsTestCaseAnswerer();
const isDescribe = astUtils.buildIsDescribeAnswerer();
function report(callExpression, message) {
context.report({
message,
node: callExpression.callee
});
}
function isNestedTest(_isTestCase, _isDescribe, nestingLevel) {
const isNested = nestingLevel > 0;
const isTest = _isTestCase || _isDescribe;
return isNested && isTest;
}
function checkForAndReportErrors(
node,
_isTestCase,
_isDescribe,
isHookCall
) {
if (isNestedTest(_isTestCase, _isDescribe, testNestingLevel)) {
const message = _isDescribe ?
'Unexpected suite nested within a test.' :
'Unexpected test nested within another test.';
report(node, message);
} else if (
isNestedTest(_isTestCase, isHookCall, hookCallNestingLevel)
) {
const message = isHookCall ?
'Unexpected test hook nested within a test hook.' :
'Unexpected test nested within a test hook.';
report(node, message);
}
}
return {
CallExpression(node) {
const _isTestCase = isTestCase(node);
const isHookCall = astUtils.isHookCall(node);
const _isDescribe = isDescribe(node);
checkForAndReportErrors(
node,
_isTestCase,
_isDescribe,
isHookCall
);
if (_isTestCase) {
testNestingLevel += 1;
} else if (isHookCall) {
hookCallNestingLevel += 1;
}
},
'CallExpression:exit'(node) {
if (isTestCase(node)) {
testNestingLevel -= 1;
} else if (astUtils.isHookCall(node)) {
hookCallNestingLevel -= 1;
}
}
};
}
};