From fbbc1e8f3611b27cd4a0b332f15b39c79b1eac09 Mon Sep 17 00:00:00 2001 From: Gareth Jones Date: Sun, 20 Sep 2020 09:14:37 +1200 Subject: [PATCH] fix(no-if): check both types of function expression Fixes #670 --- src/rules/__tests__/no-if.test.ts | 49 +++++++++++++++++++++++++------ src/rules/no-if.ts | 10 ++++--- 2 files changed, 46 insertions(+), 13 deletions(-) diff --git a/src/rules/__tests__/no-if.test.ts b/src/rules/__tests__/no-if.test.ts index add385f14..5b91441ab 100644 --- a/src/rules/__tests__/no-if.test.ts +++ b/src/rules/__tests__/no-if.test.ts @@ -13,15 +13,20 @@ const ruleTester = new TSESLint.RuleTester({ ruleTester.run('conditional expressions', rule, { valid: [ 'const x = y ? 1 : 0', - { - code: dedent` - it('foo', () => { - const foo = function(bar) { - return foo ? bar : null; - }; - }); - `, - }, + dedent` + it('foo', () => { + const foo = function (bar) { + return foo ? bar : null; + }; + }); + `, + dedent` + it('foo', function () { + const foo = function (bar) { + return foo ? bar : null; + }; + }); + `, ], invalid: [ { @@ -341,6 +346,19 @@ ruleTester.run('switch statements', rule, { }, ], }, + { + code: dedent` + xtest('foo', function () { + switch('bar') {} + }) + `, + errors: [ + { + data: { condition: 'switch' }, + messageId: 'conditionalInTest', + }, + ], + }, { code: dedent` describe('foo', () => { @@ -586,6 +604,19 @@ ruleTester.run('if statements', rule, { }, ], }, + { + code: dedent` + it.skip('foo', function () { + if('bar') {} + }) + `, + errors: [ + { + data: { condition: 'if' }, + messageId: 'conditionalInTest', + }, + ], + }, { code: dedent` it.concurrent.skip('foo', () => { diff --git a/src/rules/no-if.ts b/src/rules/no-if.ts index ded7101a9..664a27955 100644 --- a/src/rules/no-if.ts +++ b/src/rules/no-if.ts @@ -23,7 +23,9 @@ const testCaseNames = new Set([ 'fit.concurrent', ]); -const isTestArrowFunction = (node: TSESTree.ArrowFunctionExpression) => +const isTestFunctionExpression = ( + node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionExpression, +) => node.parent !== undefined && node.parent.type === AST_NODE_TYPES.CallExpression && testCaseNames.has(getNodeName(node.parent.callee)); @@ -77,8 +79,8 @@ export default createRule({ stack.push(true); } }, - FunctionExpression() { - stack.push(false); + FunctionExpression(node) { + stack.push(isTestFunctionExpression(node)); }, FunctionDeclaration(node) { const declaredVariables = context.getDeclaredVariables(node); @@ -89,7 +91,7 @@ export default createRule({ stack.push(testCallExpressions.length > 0); }, ArrowFunctionExpression(node) { - stack.push(isTestArrowFunction(node)); + stack.push(isTestFunctionExpression(node)); }, IfStatement: validate, SwitchStatement: validate,