Usage:
npm install -g jscodeshift
jscodeshift -t ava2mocha.js $(find src server -name '*.spec.js')
/* eslint-disable */ | |
function renameAssertion(name, newName, j, ast) { | |
ast.find(j.CallExpression, { | |
callee: { | |
object: { name: 't' }, | |
property: { name } | |
} | |
}).forEach((call) => { | |
call.get('callee').get('property').replace(j.identifier(newName)); | |
call.get('callee').get('object').replace(j.identifier('assert')); | |
}); | |
} | |
function renameImport(id, newId, source, newSource, j, ast) { | |
ast.find(j.ImportDeclaration, { | |
source: { value: source } | |
}).forEach((i) => { | |
i.get('source').replace(j.literal(newSource)); | |
i.get('specifiers').get(0).replace(j.importDefaultSpecifier(j.identifier(newId))); | |
}); | |
} | |
function renameCall(name, newName, j, ast) { | |
ast.find(j.CallExpression, { | |
callee: { name } | |
}).forEach((call) => { | |
call.get('callee').replace(j.identifier(newName)); | |
}); | |
} | |
function removeCallbackArg(name, arg, j, ast) { | |
ast.find(j.CallExpression, { | |
callee: { name } | |
}) | |
.filter(call => ( | |
call.value.arguments.length === 2 && | |
call.value.arguments[1].type === 'ArrowFunctionExpression' && | |
call.value.arguments[1].params.length === 1 && | |
call.value.arguments[1].params[0].name === arg | |
)) | |
.forEach((call) => { | |
call.get('arguments').get(1).get('params').replace([]); | |
}); | |
} | |
function wrap(child, parent, file, j, ast) { | |
const its = ast.find(j.ExpressionStatement, { | |
expression: { | |
callee: { name: child } | |
} | |
}); | |
const last = its.get(its.length - 1); | |
if (its.length > 0 && last.parent.name === 'program') { | |
const body = []; | |
its.forEach(it => body.push(it.value)); | |
const describe = j.expressionStatement(j.callExpression( | |
j.identifier(parent), | |
[j.literal(file.path), j.arrowFunctionExpression([], j.blockStatement(body))] | |
)); | |
last.parentPath.insertAfter(describe); | |
its.remove(); | |
} | |
} | |
module.exports = function (file, api) { | |
const j = api.jscodeshift; | |
const ast = j(file.source); | |
// Convert import from ava to assert. | |
renameImport('test', 'assert', 'ava', 'assert', j, ast); | |
// Convert (t) => {} to () => {} | |
removeCallbackArg('test', 't', j, ast); | |
// Rename test() as it(). | |
renameCall('test', 'it', j, ast); | |
// Rename assertions. | |
renameAssertion('is', 'strictEqual', j, ast); | |
renameAssertion('true', 'ok', j, ast); | |
renameAssertion('deepEqual', 'deepEqual', j, ast); | |
// Wrap it() calls with describe() | |
wrap('it', 'describe', file, j, ast); | |
return ast.toSource({ quote: 'single' }); | |
}; |