Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created July 7, 2020 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpipowitch/0b8532cf03425d22fbc5af8563bda38c to your computer and use it in GitHub Desktop.
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.)
// @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