Skip to content
Permalink
Browse files

Fix: prefer-const produces invalid autofix (fixes #11699) (#11827)

  • Loading branch information...
mdjermanovic authored and mysticatea committed Jul 17, 2019
1 parent cb475fd commit 2dafe2d288d1e0d353bb938d12a5da888091cfdb
Showing with 28 additions and 4 deletions.
  1. +9 −3 lib/rules/prefer-const.js
  2. +19 −1 tests/lib/rules/prefer-const.js
@@ -420,8 +420,9 @@ module.exports = {

let shouldFix = varDeclParent &&

// Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop)
(varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) &&
// Don't do a fix unless all variables in the declarations are initialized (or it's in a for-in or for-of loop)
(varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" ||
varDeclParent.declarations.every(declaration => declaration.init)) &&

/*
* If options.destructuring is "all", then this warning will not occur unless
@@ -450,7 +451,12 @@ module.exports = {
node,
messageId: "useConst",
data: node,
fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null
fix: shouldFix
? fixer => fixer.replaceText(
sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind),
"const"
)
: null
});
});
}
@@ -508,7 +508,25 @@ ruleTester.run("prefer-const", rule, {
{ message: "'a' is never reassigned. Use 'const' instead.", type: "Identifier" },
{ message: "'b' is never reassigned. Use 'const' instead.", type: "Identifier" }
]
}
},

// https://github.com/eslint/eslint/issues/11699
{
code: "let {a, b} = c, d;",
output: null,
errors: [
{ messageId: "useConst", data: { name: "a" }, type: "Identifier" },
{ messageId: "useConst", data: { name: "b" }, type: "Identifier" }
]
},
{
code: "let {a, b, c} = {}, e, f;",
output: null,
errors: [
{ messageId: "useConst", data: { name: "a" }, type: "Identifier" },
{ messageId: "useConst", data: { name: "b" }, type: "Identifier" },
{ messageId: "useConst", data: { name: "c" }, type: "Identifier" }
]
}
]
});

0 comments on commit 2dafe2d

Please sign in to comment.
You can’t perform that action at this time.