Skip to content

Instantly share code, notes, and snippets.

@Sinewyk
Last active April 28, 2016 20:49
Show Gist options
  • Select an option

  • Save Sinewyk/9ca994291be360a63495 to your computer and use it in GitHub Desktop.

Select an option

Save Sinewyk/9ca994291be360a63495 to your computer and use it in GitHub Desktop.
remove arrow function from mocha tests
const _ = require('underscore');
const printOptions = {
quote: 'single',
trailingComma: true,
};
const mochaFunctions = [
'describe',
'it',
'before',
'after',
'beforeEach',
'afterEach',
'context',
];
const isMochaLike = functionName => _.contains(mochaFunctions, functionName);
module.exports = function transform(file, api) {
const source = file.source;
const j = api.jscodeshift;
const root = j(source);
const isArrowFunction = n => n.type === j.ArrowFunctionExpression.toString();
const filterMochaFunctionsCall = p => {
const n = p.node;
return n.callee.type === j.Identifier.toString() &&
isMochaLike(n.callee.name);
};
root.find(j.CallExpression)
.filter(filterMochaFunctionsCall)
.map(p => {
const args = p.get('arguments').value;
const indexOfArrowFunction = _.findIndex(args, isArrowFunction);
// if we didn't find an arrow function, exclude the result
if (indexOfArrowFunction === -1) {
return null;
}
return p.get('arguments').get(indexOfArrowFunction);
})
.replaceWith(p => {
// replace with anonymous function expression
// with same arguments list and same body
return j.functionExpression(null, p.get('params').value, p.get('body').value);
});
return root.toSource(printOptions);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment