diff --git a/src/rules/cognitive-complexity.ts b/src/rules/cognitive-complexity.ts index 6f0b68a0..114501d0 100644 --- a/src/rules/cognitive-complexity.ts +++ b/src/rules/cognitive-complexity.ts @@ -113,6 +113,9 @@ const rule: TSESLint.RuleModule /** Stack of enclosing functions */ const enclosingFunctions: TSESTree.FunctionLike[] = []; + /** Indicator if inside a JSX expression */ + let jsx = false; + let secondLevelFunctions: Array<{ node: TSESTree.FunctionLike; parent: TSESTree.Node | undefined; @@ -153,7 +156,12 @@ const rule: TSESLint.RuleModule }); } }, - + 'JSXElement,JSXFragment'() { + jsx = true; + }, + 'JSXElement,JSXFragment:exit'() { + jsx = false; + }, IfStatement(node: TSESTree.Node) { visitIfStatement(node as TSESTree.IfStatement); }, @@ -339,6 +347,10 @@ const rule: TSESLint.RuleModule } function visitLogicalExpression(logicalExpression: TSESTree.LogicalExpression) { + if (jsx) { + return; + } + if (!consideredLogicalExpressions.has(logicalExpression)) { const flattenedLogicalExpressions = flattenLogicalExpression(logicalExpression); diff --git a/tests/rules/cognitive-complexity.test.ts b/tests/rules/cognitive-complexity.test.ts index aa588848..c51816b0 100644 --- a/tests/rules/cognitive-complexity.test.ts +++ b/tests/rules/cognitive-complexity.test.ts @@ -22,7 +22,51 @@ import { ruleTester } from '../rule-tester'; import rule = require('../../src/rules/cognitive-complexity'); ruleTester.run('cognitive-complexity', rule, { - valid: [{ code: `function zero_complexity() {}`, options: [0] }], + valid: [ + { code: `function zero_complexity() {}`, options: [0] }, + { + code: ` + function Component(obj) { + return ( + { obj.title?.text } + ); + }`, + parserOptions: { ecmaFeatures: { jsx: true } }, + options: [0], + }, + { + code: ` + function Component(obj) { + return ( + <> + { obj.isFriendly && Welcome } + + ); + }`, + parserOptions: { ecmaFeatures: { jsx: true } }, + options: [0], + }, + { + code: ` + function Component(obj) { + return ( + Text + ); + }`, + parserOptions: { ecmaFeatures: { jsx: true } }, + options: [0], + }, + { + code: ` + function Component(obj) { + return ( + + ); + }`, + parserOptions: { ecmaFeatures: { jsx: true } }, + options: [0], + }, + ], invalid: [ // if {