Jack Franklin | 8b9aa2f | 2020-02-12 16:35:15 +0000 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | /* eslint "complexity": [ "error", 5 ] */ |
| 4 | |
| 5 | const astUtils = require('../util/ast'); |
| 6 | const { additionalSuiteNames } = require('../util/settings'); |
| 7 | |
| 8 | module.exports = function noNestedTests(context) { |
| 9 | const settings = context.settings; |
| 10 | let testNestingLevel = 0; |
| 11 | let hookCallNestingLevel = 0; |
| 12 | |
| 13 | function report(callExpression, message) { |
| 14 | context.report({ |
| 15 | message, |
| 16 | node: callExpression.callee |
| 17 | }); |
| 18 | } |
| 19 | |
| 20 | function isNestedTest(isTestCase, isDescribe, nestingLevel) { |
| 21 | const isNested = nestingLevel > 0; |
| 22 | const isTest = isTestCase || isDescribe; |
| 23 | |
| 24 | return isNested && isTest; |
| 25 | } |
| 26 | |
| 27 | function checkForAndReportErrors(node, isTestCase, isDescribe, isHookCall) { |
| 28 | if (isNestedTest(isTestCase, isDescribe, testNestingLevel)) { |
| 29 | const message = isDescribe ? |
| 30 | 'Unexpected suite nested within a test.' : |
| 31 | 'Unexpected test nested within another test.'; |
| 32 | report(node, message); |
| 33 | } else if (isNestedTest(isTestCase, isHookCall, hookCallNestingLevel)) { |
| 34 | const message = isHookCall ? |
| 35 | 'Unexpected test hook nested within a test hook.' : |
| 36 | 'Unexpected test nested within a test hook.'; |
| 37 | report(node, message); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | return { |
| 42 | CallExpression(node) { |
| 43 | const isTestCase = astUtils.isTestCase(node); |
| 44 | const isHookCall = astUtils.isHookCall(node); |
| 45 | const isDescribe = astUtils.isDescribe(node, additionalSuiteNames(settings)); |
| 46 | |
| 47 | checkForAndReportErrors(node, isTestCase, isDescribe, isHookCall); |
| 48 | |
| 49 | if (isTestCase) { |
| 50 | testNestingLevel += 1; |
| 51 | } else if (isHookCall) { |
| 52 | hookCallNestingLevel += 1; |
| 53 | } |
| 54 | }, |
| 55 | |
| 56 | 'CallExpression:exit'(node) { |
| 57 | if (astUtils.isTestCase(node)) { |
| 58 | testNestingLevel -= 1; |
| 59 | } else if (astUtils.isHookCall(node)) { |
| 60 | hookCallNestingLevel -= 1; |
| 61 | } |
| 62 | } |
| 63 | }; |
| 64 | }; |