Skip to content

Instantly share code, notes, and snippets.

@Raizan
Last active September 8, 2021 21:32
Show Gist options
  • Save Raizan/fcc212660b493564ecbf743a8897f8f4 to your computer and use it in GitHub Desktop.
Save Raizan/fcc212660b493564ecbf743a8897f8f4 to your computer and use it in GitHub Desktop.
Code fix
/**
* Transform Mocha test file
* from legacy local convention into
* test filtering ready file
*
* @param {string} testFileContent
* @returns transfomed code
*/
function transform(testFileContent) {
// use @babel/parser
const ast = recast.parse(testFileContent.toString());
const types = recast.types;
const n = types.namedTypes;
const b = types.builders;
const itNodes = [];
const transformedItNodes = [];
recast.visit(ast, {
visitCallExpression(path) {
if (path.node.callee.name === "it") {
itNodes.push(path.node);
}
this.traverse(path);
}
});
for (let node of itNodes) {
let issue;
let severity;
recast.visit(node, {
visitCallExpression(path) {
const callee = path.node.callee;
if (!n.Identifier.check(callee) && n.MemberExpression.check(callee)) {
if (callee.property.name === "setIssue") {
const literalArgument = path.parent.node.expression.arguments[1];
issue = n.Literal.check(literalArgument) ? literalArgument.value : null;
path.parent.prune();
} else if (callee.property.name === "setSeverity") {
const literalArgument = path.parent.node.expression.arguments[1];
severity = n.Literal.check(literalArgument) ? literalArgument.value : null;
path.parent.prune();
}
}
this.traverse(path);
}
});
if (severity) {
node.arguments[0].value += ` !${severity}`;
}
if (issue) {
node.arguments[0].value += ` %${issue}`;
}
transformedItNodes.push(b.expressionStatement(node));
}
recast.visit(ast, {
visitCallExpression(path) {
if (
path.node.callee.name === "describe" &&
n.Literal.check(path.node.arguments[0]) &&
/(#smoke|#negative)/.test(path.node.arguments[0].value)
) {
path.prune();
}
this.traverse(path);
}
});
recast.visit(ast, {
visitCallExpression(path) {
if (
path.node.callee.name === "describe" &&
n.FunctionExpression.check(path.node.arguments[1])
) {
path.node.arguments[1].body.body = [
...path.node.arguments[1].body.body,
...transformedItNodes
];
}
return false;
}
});
return recast.print(ast).code;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment