blob: 089bfdff8f3e5d7487064eb5e1d55c7b611971d5 [file] [log] [blame]
Jack Franklin8b9aa2f2020-02-12 16:35:15 +00001'use strict';
2
3/* eslint "complexity": [ "error", 5 ] */
4
Tim van der Lippe16aca392020-11-13 11:37:13 +00005const createAstUtils = require('../util/ast');
Jack Franklin8b9aa2f2020-02-12 16:35:15 +00006
Tim van der Lippe16aca392020-11-13 11:37:13 +00007module.exports = {
8 meta: {
9 type: 'problem',
10 docs: {
11 description: 'Disallow tests to be nested within other tests '
Jack Franklin8b9aa2f2020-02-12 16:35:15 +000012 }
Tim van der Lippe16aca392020-11-13 11:37:13 +000013 },
14 create(context) {
15 const astUtils = createAstUtils(context.settings);
16 let testNestingLevel = 0;
17 let hookCallNestingLevel = 0;
Jack Franklin8b9aa2f2020-02-12 16:35:15 +000018
Tim van der Lippe16aca392020-11-13 11:37:13 +000019 function report(callExpression, message) {
20 context.report({
21 message,
22 node: callExpression.callee
23 });
24 }
Jack Franklin8b9aa2f2020-02-12 16:35:15 +000025
Tim van der Lippe16aca392020-11-13 11:37:13 +000026 function isNestedTest(isTestCase, isDescribe, nestingLevel) {
27 const isNested = nestingLevel > 0;
28 const isTest = isTestCase || isDescribe;
Jack Franklin8b9aa2f2020-02-12 16:35:15 +000029
Tim van der Lippe16aca392020-11-13 11:37:13 +000030 return isNested && isTest;
31 }
Jack Franklin8b9aa2f2020-02-12 16:35:15 +000032
Tim van der Lippe16aca392020-11-13 11:37:13 +000033 function checkForAndReportErrors(node, isTestCase, isDescribe, isHookCall) {
34 if (isNestedTest(isTestCase, isDescribe, testNestingLevel)) {
35 const message = isDescribe ?
36 'Unexpected suite nested within a test.' :
37 'Unexpected test nested within another test.';
38 report(node, message);
39 } else if (isNestedTest(isTestCase, isHookCall, hookCallNestingLevel)) {
40 const message = isHookCall ?
41 'Unexpected test hook nested within a test hook.' :
42 'Unexpected test nested within a test hook.';
43 report(node, message);
Jack Franklin8b9aa2f2020-02-12 16:35:15 +000044 }
45 }
Tim van der Lippe16aca392020-11-13 11:37:13 +000046
47 return {
48 CallExpression(node) {
49 const isTestCase = astUtils.isTestCase(node);
50 const isHookCall = astUtils.isHookCall(node);
51 const isDescribe = astUtils.isDescribe(node);
52
53 checkForAndReportErrors(node, isTestCase, isDescribe, isHookCall);
54
55 if (isTestCase) {
56 testNestingLevel += 1;
57 } else if (isHookCall) {
58 hookCallNestingLevel += 1;
59 }
60 },
61
62 'CallExpression:exit'(node) {
63 if (astUtils.isTestCase(node)) {
64 testNestingLevel -= 1;
65 } else if (astUtils.isHookCall(node)) {
66 hookCallNestingLevel -= 1;
67 }
68 }
69 };
70 }
Jack Franklin8b9aa2f2020-02-12 16:35:15 +000071};