Skip to content

Instantly share code, notes, and snippets.

@eddiecooro
Created August 28, 2023 14:44
Show Gist options
  • Save eddiecooro/941138c2a8695a9b3a3b86773009d8c9 to your computer and use it in GitHub Desktop.
Save eddiecooro/941138c2a8695a9b3a3b86773009d8c9 to your computer and use it in GitHub Desktop.
A codemod that adds a unique `data-testid` to a list of jsx components that are imported from a specific path
// addUuidToButton.js
const j = require("jscodeshift");
const crypto = require("crypto");
function generateUUID(filePath, position) {
const str = filePath + JSON.stringify(position);
return crypto.createHash("md5").update(str).digest("hex").substr(0, 5);
}
const importPaths = ["components"];
const components = ["Button", "ToggleButton"];
module.exports = function (fileInfo, api) {
const j = api.jscodeshift;
const root = j(fileInfo.source);
let isComponentImported = false;
const importDeclarations = root.find(j.ImportDeclaration);
importDeclarations.forEach(dec => {
const source = dec?.value?.source;
if (
source?.type === "StringLiteral" &&
importPaths.includes(source?.value)
) {
isComponentImported = true;
}
});
if (!isComponentImported) {
return fileInfo.source;
}
components.forEach(component => {
root
.find(j.JSXElement, {
openingElement: {
name: {
name: component,
},
},
})
.forEach(path => {
const existingProps = path.node.openingElement.attributes;
if (
existingProps.some(
prop => prop.name && prop.name.name === "data-testid",
)
) {
return;
}
const newUuidProp = j.jsxAttribute(
j.jsxIdentifier("data-testid"),
j.stringLiteral(generateUUID(fileInfo.path, path.node.loc.start)),
);
existingProps.push(newUuidProp);
});
});
return root.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment