Skip to content

Instantly share code, notes, and snippets.

@DanielMSchmidt
Last active February 27, 2018 09:53
Show Gist options
  • Save DanielMSchmidt/9e1bc548ab5d8d1a3fadddc2d735f8c2 to your computer and use it in GitHub Desktop.
Save DanielMSchmidt/9e1bc548ab5d8d1a3fadddc2d735f8c2 to your computer and use it in GitHub Desktop.
Remove this from tests

Run this on your tests to remove every this.foo from the tests

npm install -g jscodeshift

jscodeshift --transform https://gist.githubusercontent.com/DanielMSchmidt/9e1bc548ab5d8d1a3fadddc2d735f8c2/raw/808d337f6088ff62feae99115edaf59a6c333b1a/transform.js ./**/__tests__/*.js
"use strict";
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = function(file, api) {
const j = api.jscodeshift;
const ast = j(file.source);
const variablesInFile = {};
const possibleExpressionTypes = [j.MemberExpression, j.JSXMemberExpression];
possibleExpressionTypes.forEach(expression => {
// rename this.foo to foo
ast
.find(expression)
.filter(
p =>
(p.value.object && p.value.object.type === "ThisExpression") ||
(p.value.object.type === "JSXIdentifier" &&
p.value.object.name === "this")
)
.replaceWith(p => {
const property = p.value.property;
// rename foo to thisFoo to avoid name conflicts
property.name = "this" + capitalizeFirstLetter(property.name);
return property;
})
.forEach(p => {
variablesInFile[p.value.name] = true;
});
});
if (Object.keys(variablesInFile).length > 0) {
// Add let foo; statements before describe block
ast
.find(j.ExpressionStatement)
.filter(
p =>
p.value.expression &&
p.value.expression.callee &&
p.value.expression.callee.name === "describe"
)
.at(0)
.insertBefore([
j.variableDeclaration(
"let",
Object.keys(variablesInFile).map(variable =>
j.variableDeclarator(j.identifier(variable), null)
)
)
]);
}
return ast.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment