Created
May 12, 2023 14:17
-
-
Save SrinivasanTarget/baaed175e72b66b15282f766615efb30 to your computer and use it in GitHub Desktop.
jest to mocha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const methodMap = { | |
suite: 'describe', | |
context: 'describe', | |
test: 'it', | |
it: 'it', | |
beforeAll: 'before', | |
beforeEach: 'beforeEach', | |
afterAll: 'after', | |
afterEach: 'afterEach', | |
}; | |
const jestMethodsWithDescriptionsAllowed = new Set(['it', 'test', 'describe']); | |
const methodModifiers = ['only', 'skip']; | |
function hasBinding(name, scope) { | |
if (!scope) { | |
return false; | |
} | |
const bindings = Object.keys(scope.getBindings()) || []; | |
if (bindings.indexOf(name) >= 0) { | |
return true; | |
} | |
return scope.isGlobal ? false : hasBinding(name, scope.parent); | |
} | |
function jestToMocha(fileInfo, api, options) { | |
const j = api.jscodeshift; | |
const ast = j(fileInfo.source); | |
Object.keys(methodMap).forEach((mochaMethod) => { | |
const jestMethod = methodMap[mochaMethod]; | |
ast | |
.find(j.CallExpression, { | |
type: 'CallExpression', | |
callee: { type: 'Identifier', name: jestMethod }, | |
}) | |
.filter(({ scope }) => !hasBinding(jestMethod, scope)) | |
.replaceWith((path) => { | |
let args = path.value.arguments; | |
if (!jestMethodsWithDescriptionsAllowed.has(jestMethod)) { | |
args = args.filter((a) => a.type !== 'Literal'); | |
} else if (args.length === 1 && args[0].type === 'Literal') { | |
const emptyFunctionExpression = j.functionExpression( | |
null, | |
[], | |
j.blockStatement([]) | |
); | |
return j.callExpression( | |
j.memberExpression(j.identifier(mochaMethod), j.identifier('skip')), | |
args.concat([emptyFunctionExpression]) | |
); | |
} | |
return j.callExpression(j.identifier(mochaMethod), args); | |
}); | |
methodModifiers.forEach((modifier) => { | |
ast | |
.find(j.CallExpression, { | |
type: 'CallExpression', | |
callee: { | |
type: 'MemberExpression', | |
object: { type: 'Identifier', name: jestMethod }, | |
property: { type: 'Identifier', name: modifier }, | |
}, | |
}) | |
.replaceWith((path) => | |
j.callExpression( | |
j.memberExpression(j.identifier(mochaMethod), j.identifier(modifier)), | |
path.value.arguments | |
) | |
); | |
}); | |
}); | |
return ast.toSource(); | |
} | |
export default jestToMocha; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment