Created
April 11, 2023 23:49
-
-
Save gabrielcsapo/9e2d8914b54d0ca922265f49d8f7e87a to your computer and use it in GitHub Desktop.
jscodeshift update assert.expect
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
export default function transformer(file, api) { | |
const j = api.jscodeshift; | |
return j(file.source) | |
.find(j.CallExpression, { | |
callee: { | |
type: 'Identifier', | |
name: 'test', | |
}, | |
}) | |
.forEach((path) => { | |
const assertCall = j.memberExpression( | |
j.identifier('assert'), | |
j.identifier('expect') | |
); | |
const assertUsage = j(path.node.arguments[1].body).find(j.Identifier, { | |
name: 'assert', | |
}).length; | |
if (assertUsage > 0) { | |
const assertStatement = j.expressionStatement( | |
j.callExpression(assertCall, [j.literal(assertUsage)]) | |
); | |
const existingExpectCalls = j(path.node.arguments[1].body) | |
.find(j.CallExpression, { callee: assertCall }) | |
.forEach((callPath) => { | |
const arg = callPath.node.arguments[0]; | |
if (j.Literal.check(arg) && typeof arg.value === 'number') { | |
arg.value += assertUsage; | |
} else { | |
const addition = j.binaryExpression( | |
'+', | |
arg, | |
j.literal(assertUsage) | |
); | |
callPath.node.arguments[0] = addition; | |
} | |
}); | |
const blockStatement = path.node.arguments[1].body; | |
j(blockStatement).find(j.Statement).at(0).insertBefore(assertStatement); | |
} else { | |
const assertStatement = j.variableDeclaration('const', [ | |
j.variableDeclarator( | |
j.identifier('assert'), | |
j.memberExpression( | |
j.callExpression(j.identifier('require'), [j.literal('assert')]), | |
j.identifier('strict') | |
) | |
), | |
]); | |
const assertExpectCall = j.callExpression(assertCall, [j.literal(0)]); | |
const assertExpectStatement = j.expressionStatement(assertExpectCall); | |
const blockStatement = path.node.arguments[1].body; | |
j(blockStatement) | |
.find(j.Statement) | |
.at(0) | |
.insertBefore(assertExpectStatement); | |
j(blockStatement).find(j.Statement).at(0).insertBefore(assertStatement); | |
} | |
}) | |
.toSource(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment