diff --git a/lib/rules/no-cond-assign.js b/lib/rules/no-cond-assign.js index 67dcd28b208..b1d40f9c8b2 100644 --- a/lib/rules/no-cond-assign.js +++ b/lib/rules/no-cond-assign.js @@ -2,10 +2,21 @@ * @fileoverview Rule to flag assignment in a conditional statement's test expression * @author Stephen Murray */ + "use strict"; +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + const astUtils = require("./utils/ast-utils"); +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const TEST_CONDITION_PARENT_TYPES = new Set(["IfStatement", "WhileStatement", "DoWhileStatement", "ForStatement", "ConditionalExpression"]); + const NODE_DESCRIPTIONS = { DoWhileStatement: "a 'do...while' statement", ForStatement: "a 'for' statement", @@ -55,7 +66,7 @@ module.exports = { */ function isConditionalTestExpression(node) { return node.parent && - node.parent.test && + TEST_CONDITION_PARENT_TYPES.has(node.parent.type) && node === node.parent.test; } diff --git a/tests/lib/rules/no-cond-assign.js b/tests/lib/rules/no-cond-assign.js index 39af0eed234..372b81c1bf7 100644 --- a/tests/lib/rules/no-cond-assign.js +++ b/tests/lib/rules/no-cond-assign.js @@ -41,7 +41,10 @@ ruleTester.run("no-cond-assign", rule, { { code: "if (function(node) { return node = parentNode; }) { }", options: ["except-parens"] }, { code: "if (function(node) { return node = parentNode; }) { }", options: ["always"] }, { code: "x = 0;", options: ["always"] }, - "var x; var b = (x === 0) ? 1 : 0;" + "var x; var b = (x === 0) ? 1 : 0;", + { code: "switch (foo) { case a = b: bar(); }", options: ["except-parens"] }, + { code: "switch (foo) { case a = b: bar(); }", options: ["always"] }, + { code: "switch (foo) { case baz + (a = b): bar(); }", options: ["always"] } ], invalid: [ { code: "var x; if (x = 0) { var b = 1; }", errors: [{ messageId: "missing", type: "IfStatement", line: 1, column: 12 }] }, @@ -62,6 +65,7 @@ ruleTester.run("no-cond-assign", rule, { { code: "do { } while ((x = x + 1));", options: ["always"], errors: [{ messageId: "unexpected", data: { type: "a 'do...while' statement" }, type: "DoWhileStatement" }] }, { code: "for(; (x = y); ) { }", options: ["always"], errors: [{ messageId: "unexpected", data: { type: "a 'for' statement" }, type: "ForStatement" }] }, { code: "var x; var b = (x = 0) ? 1 : 0;", errors: [{ messageId: "missing", type: "ConditionalExpression" }] }, + { code: "var x; var b = x && (y = 0) ? 1 : 0;", options: ["always"], errors: [{ messageId: "unexpected", type: "ConditionalExpression" }] }, { code: "(((3496.29)).bkufyydt = 2e308) ? foo : bar;", errors: [{ messageId: "missing", type: "ConditionalExpression" }] } ] });