jest-codemods
Version:
Codemods for migrating test files to Jest
85 lines (84 loc) • 3.29 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var finale_1 = __importDefault(require("../utils/finale"));
var imports_1 = require("../utils/imports");
var jasmine_this_1 = __importDefault(require("./jasmine-this"));
var methodMap = {
suite: 'describe',
context: 'describe',
specify: 'test',
test: 'test',
it: 'it',
before: 'beforeAll',
beforeEach: 'beforeEach',
setup: 'beforeEach',
after: 'afterAll',
afterEach: 'afterEach',
teardown: 'afterEach',
suiteSetup: 'beforeAll',
suiteTeardown: 'afterAll',
};
var jestMethodsWithDescriptionsAllowed = new Set(['test', 'it', 'describe']);
var methodModifiers = ['only', 'skip'];
function hasBinding(name, scope) {
if (!scope) {
return false;
}
var bindings = Object.keys(scope.getBindings()) || [];
if (bindings.indexOf(name) >= 0) {
return true;
}
return scope.isGlobal ? false : hasBinding(name, scope.parent);
}
var mochaToJest = function (fileInfo, api, options) {
var j = api.jscodeshift;
var ast = j(fileInfo.source);
(0, imports_1.removeRequireAndImport)(j, ast, 'mocha');
Object.keys(methodMap).forEach(function (mochaMethod) {
var jestMethod = methodMap[mochaMethod];
ast
.find(j.CallExpression, {
type: 'CallExpression',
callee: { type: 'Identifier', name: mochaMethod },
})
.filter(function (_a) {
var scope = _a.scope;
return !hasBinding(mochaMethod, scope);
})
.replaceWith(function (path) {
var args = path.value.arguments;
if (!jestMethodsWithDescriptionsAllowed.has(jestMethod)) {
args = args.filter(function (a) { return a.type !== 'Literal'; });
}
else if (args.length === 1 && args[0].type === 'Literal') {
var emptyArrowFunction = j.arrowFunctionExpression([], j.blockStatement([j.emptyStatement()]));
return j.callExpression(j.memberExpression(j.identifier(jestMethod), j.identifier('skip')), args.concat([emptyArrowFunction]));
}
return j.callExpression(j.identifier(jestMethod), args);
});
methodModifiers.forEach(function (modifier) {
ast
.find(j.CallExpression, {
type: 'CallExpression',
callee: {
type: 'MemberExpression',
object: { type: 'Identifier', name: mochaMethod },
property: { type: 'Identifier', name: modifier },
},
})
.replaceWith(function (path) {
return j.callExpression(j.memberExpression(j.identifier(jestMethod), j.identifier(modifier)), path.value.arguments);
});
});
});
fileInfo.source = (0, finale_1.default)(fileInfo, j, ast, options);
var transformedSource = (0, jasmine_this_1.default)(fileInfo, api, options);
if (transformedSource) {
fileInfo.source = transformedSource;
}
return fileInfo.source;
};
exports.default = mochaToJest;
;