diff --git a/lib/rules/no-manual-cleanup.ts b/lib/rules/no-manual-cleanup.ts index 84a63281..abf7754d 100644 --- a/lib/rules/no-manual-cleanup.ts +++ b/lib/rules/no-manual-cleanup.ts @@ -2,7 +2,7 @@ import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils'; import { getDocsUrl } from '../utils'; import { isImportDefaultSpecifier, - isCallExpression, + isLiteral, isIdentifier, isObjectPattern, isProperty, @@ -88,40 +88,42 @@ export default ESLintUtils.RuleCreator(getDocsUrl)({ }); } }, - VariableDeclarator(node) { - if ( - isCallExpression(node.init) && - isIdentifier(node.init.callee) && - node.init.callee.name === 'require' - ) { - const requiredModule = node.init.arguments[0] as TSESTree.Literal; - const requiredModuleValue = requiredModule.value as string; - - const testingLibraryWithCleanup = requiredModuleValue.match( - CLEANUP_LIBRARY_REGEX + [`VariableDeclarator > CallExpression > Identifier[name="require"]`]( + node: TSESTree.Identifier + ) { + const { arguments: args } = node.parent as TSESTree.CallExpression; + + const literalNodeCleanupModuleName = args.find( + args => + isLiteral(args) && + typeof args.value === 'string' && + args.value.match(CLEANUP_LIBRARY_REGEX) + ); + + if (!literalNodeCleanupModuleName) { + return; + } + + const declaratorNode = node.parent + .parent as TSESTree.VariableDeclarator; + + if (isObjectPattern(declaratorNode.id)) { + const cleanupProperty = declaratorNode.id.properties.find( + property => + isProperty(property) && + isIdentifier(property.key) && + property.key.name === 'cleanup' ); - // Early return if the library doesn't support `cleanup` - if (!testingLibraryWithCleanup) { - return; + if (cleanupProperty) { + context.report({ + node: cleanupProperty, + messageId: 'noManualCleanup', + }); } - if (isObjectPattern(node.id)) { - const cleanupProperty = node.id.properties.find( - property => - isProperty(property) && - isIdentifier(property.key) && - property.key.name === 'cleanup' - ); - if (cleanupProperty) { - context.report({ - node: cleanupProperty, - messageId: 'noManualCleanup', - }); - } - } else { - defaultRequireFromTestingLibrary = node.id; - } + } else { + defaultRequireFromTestingLibrary = declaratorNode.id; } }, 'Program:exit'() { diff --git a/tests/lib/rules/no-manual-cleanup.test.ts b/tests/lib/rules/no-manual-cleanup.test.ts index 3cc994e2..bd02fb42 100644 --- a/tests/lib/rules/no-manual-cleanup.test.ts +++ b/tests/lib/rules/no-manual-cleanup.test.ts @@ -44,6 +44,9 @@ ruleTester.run(RULE_NAME, rule, { // For test coverage code: `const utils = render("something")`, }, + { + code: `const utils = require(moduleName)`, + }, ], invalid: [ ...ALL_TESTING_LIBRARIES_WITH_CLEANUP.map(lib => ({