-
Notifications
You must be signed in to change notification settings - Fork 0
/
tape-to-jest.ts
72 lines (59 loc) · 1.96 KB
/
tape-to-jest.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { ExpressionKind } from "ast-types/gen/kinds";
import {
FunctionExpression,
Identifier,
SpreadElement,
Transform,
} from "jscodeshift";
import { getExpectationInfo } from "./utils/get-expectation-info";
const transform: Transform = (fileInfo, api) => {
const j = api.jscodeshift;
const root = j(fileInfo.source);
const testExprs = root.find(j.CallExpression, {
callee: {
name: "test",
},
});
const createExpectStatement = (args: (ExpressionKind | SpreadElement)[]) =>
j.callExpression(j.identifier("expect"), args);
const createExpectCall = (
expectArgs: (ExpressionKind | SpreadElement)[],
expectationName: string,
expectationArgs: (ExpressionKind | SpreadElement)[],
negated: boolean
) => {
const innerExpr = negated
? j.memberExpression(
createExpectStatement(expectArgs),
j.identifier("not")
)
: createExpectStatement(expectArgs);
const fullMemberExpr = j.memberExpression(
innerExpr,
j.identifier(expectationName)
);
return j.callExpression(fullMemberExpr, expectationArgs);
};
testExprs.forEach((path) => {
(path.value.callee as Identifier).name = "it"; // change "test" to "it"
const assertObjectName = ((path.value.arguments[1] as FunctionExpression).params[0] as Identifier).name;
(path.value.arguments[1] as FunctionExpression).params = []; // no longer pass in assertion object
const asserts = j(path).find(j.CallExpression, {
callee: {
type: "MemberExpression",
object: { type: "Identifier", name: assertObjectName },
},
});
asserts.forEach((assertExpr) => {
const args = assertExpr.value.arguments;
const info = getExpectationInfo(assertExpr);
if (info === null) {
assertExpr.prune();
return;
}
assertExpr.replace(createExpectCall([args[0]], info.name, info.args, info.negated));
});
});
return root.toSource();
};
export default transform;