forked from babel/babel
/
conversion.js
76 lines (65 loc) 路 2.35 KB
/
conversion.js
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
73
74
75
76
import traverse from "../lib";
import { parse } from "@babel/parser";
import generate from "@babel/generator";
import * as t from "@babel/types";
function getPath(code) {
const ast = parse(code);
let path;
traverse(ast, {
Program: function (_path) {
path = _path.get("body.0");
_path.stop();
},
});
return path;
}
function generateCode(path) {
return generate(path.parentPath.node).code;
}
describe("conversion", function () {
describe("ensureBlock", function () {
it("throws converting node without body to block", function () {
const rootPath = getPath("true;");
expect(() => {
rootPath.ensureBlock();
}).toThrow();
});
it("throws converting already block array", function () {
const rootPath = getPath("function test() { true; }").get("body");
expect(() => {
rootPath.ensureBlock();
}).toThrow();
});
it("converts arrow function with expression body to block", function () {
const rootPath = getPath("() => true").get("expression");
rootPath.ensureBlock();
expect(generateCode(rootPath)).toBe("() => {\n return true;\n};");
});
it("preserves arrow function body's context", function () {
const rootPath = getPath("() => true").get("expression");
const body = rootPath.get("body");
rootPath.ensureBlock();
body.replaceWith(t.booleanLiteral(false));
expect(generateCode(rootPath)).toBe("() => {\n return false;\n};");
});
it("preserves arrow function body's context", function () {
const rootPath = getPath("() => true").get("expression");
const body = rootPath.get("body");
rootPath.ensureBlock();
body.replaceWithMultiple([t.booleanLiteral(false), t.emptyStatement()]);
expect(generateCode(rootPath)).toBe("() => {\n return false;\n};");
});
it("converts for loop with statement body to block", function () {
const rootPath = getPath("for (;;) true;");
rootPath.ensureBlock();
expect(generateCode(rootPath)).toBe("for (;;) {\n true;\n}");
});
it("preserves for loop body's context", function () {
const rootPath = getPath("for (;;) true;");
const body = rootPath.get("body");
rootPath.ensureBlock();
body.replaceWith(t.booleanLiteral(false));
expect(generateCode(rootPath)).toBe("for (;;) {\n false;\n}");
});
});
});