Created
July 7, 2020 07:38
-
-
Save donaldpipowitch/0b8532cf03425d22fbc5af8563bda38c to your computer and use it in GitHub Desktop.
ESLint rule to check for round brackets in Jest `test` names. (Doesn't play nicely with --testNamePattern without escaping.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @ts-check | |
/** @type {import("eslint").Rule.RuleModule} */ | |
const rule = { | |
meta: { | |
docs: { | |
description: `If you use a Jest test name like "hello (world)" you can't run \`$ jest -t "hello (world)"\` to select this test.`, | |
}, | |
fixable: 'code', | |
}, | |
create(context) { | |
return { | |
CallExpression(node) { | |
// 1) for every function called 'test' | |
if (node.type !== 'CallExpression') return; | |
if (node.callee.type !== 'Identifier') return; | |
if (node.callee.name !== 'test') return; | |
// 2) check if the first param is a string containing `()` | |
const firstParam = node.arguments[0]; | |
if (!firstParam) return; | |
if (firstParam.type !== 'Literal') return; | |
const { value } = firstParam; | |
if (typeof value !== 'string') return; | |
if (!value.includes('(') && !value.includes(')')) return; | |
// 3) report warning and offer a fix | |
context.report({ | |
node: firstParam, | |
message: `The usage of "(" and ")" in test names is not allowed.`, | |
fix(fixer) { | |
return fixer.replaceText( | |
firstParam, | |
`'${value.replace(/\)/g, '').replace(/\(/g, '')}'` | |
); | |
}, | |
}); | |
}, | |
}; | |
}, | |
}; | |
module.exports = rule; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment