Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save liaujianjie/c57a93c4126d9e52edea6f0eef17e661 to your computer and use it in GitHub Desktop.
Save liaujianjie/c57a93c4126d9e52edea6f0eef17e661 to your computer and use it in GitHub Desktop.
import _ from "lodash";
/**
* jscodeshift codemod to rename Jest test files for classes from:
* ```
* describe(MyCat, () => {
* describe("meow", () => { ... });
* });
* ```
* to:
* ```
* describe(MyCat, () => {
* describe(MyCat.prototype.meow, () => { ... });
* });
* ```
*/
export default function transformer(file, { jscodeshift: j }) {
return j(file.source)
.find(j.CallExpression, {
callee: { type: "Identifier", name: "describe" },
})
.forEach((topPath) =>
j(topPath.node.arguments)
.find(j.CallExpression, { callee: { type: "Identifier", name: "describe" } })
.filter((path) => path.node.arguments[0].type === "StringLiteral")
.find(j.Literal)
.at(0)
.replaceWith((node) => {
const className = topPath.node.arguments[0].name;
const methodName = node.value.value;
assertValidMethodName(methodName);
const methodIdenfier = `${className}.prototype.${methodName}`;
return j.identifier(methodIdenfier);
})
)
.toSource();
}
function assertValidMethodName(string) {
if (containsWhitespace(string)) {
throw new Error(`"${string}" contains whitespace!`);
}
if (!isCamelCase(string)) {
throw new Error(`"${string}" is not in camel case!`);
}
return true;
}
function containsWhitespace(string) {
return /\s/g.test(string);
}
function isCamelCase(str) {
return _.camelCase(str) === str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment