| 1 | import { parse } from "@babel/parser"; |
| 2 | import * as t from "@babel/types"; |
| 3 | |
| 4 | import _traverse from "../lib/index.js"; |
| 5 | import _generate from "@babel/generator"; |
| 6 | const traverse = _traverse.default || _traverse; |
| 7 | const generate = _generate.default || _generate; |
| 8 | |
| 9 | function getPath(code) { |
| 10 | const ast = parse(code); |
| 11 | let path; |
| 12 | traverse(ast, { |
| 13 | Program: function (_path) { |
| 14 | path = _path.get("body.0"); |
| 15 | _path.stop(); |
| 16 | }, |
| 17 | }); |
| 18 | |
| 19 | return path; |
| 20 | } |
| 21 | |
| 22 | function generateCode(path) { |
| 23 | return generate(path.parentPath.node).code; |
| 24 | } |
| 25 | |
| 26 | describe("conversion", function () { |
| 27 | describe("ensureBlock", function () { |
| 28 | it("throws converting node without body to block", function () { |
| 29 | const rootPath = getPath("true;"); |
| 30 | |
| 31 | expect(() => { |
| 32 | rootPath.ensureBlock(); |
| 33 | }).toThrow(); |
| 34 | }); |
| 35 | |
| 36 | it("throws converting already block array", function () { |
| 37 | const rootPath = getPath("function test() { true; }").get("body"); |
| 38 | expect(() => { |
| 39 | rootPath.ensureBlock(); |
| 40 | }).toThrow(); |
| 41 | }); |
| 42 | |
| 43 | it("converts arrow function with expression body to block", function () { |
| 44 | const rootPath = getPath("() => true").get("expression"); |
| 45 | rootPath.ensureBlock(); |
| 46 | expect(generateCode(rootPath)).toBe("() => {\n return true;\n};"); |
| 47 | }); |
| 48 | |
| 49 | it("preserves arrow function body's context", function () { |
| 50 | const rootPath = getPath("() => true").get("expression"); |
| 51 | const body = rootPath.get("body"); |
| 52 | rootPath.ensureBlock(); |
| 53 | body.replaceWith(t.booleanLiteral(false)); |
| 54 | expect(generateCode(rootPath)).toBe("() => {\n return false;\n};"); |
| 55 | }); |
| 56 | |
| 57 | it("preserves arrow function body's context", function () { |
| 58 | const rootPath = getPath("() => true").get("expression"); |
| 59 | const body = rootPath.get("body"); |
| 60 | rootPath.ensureBlock(); |
| 61 | body.replaceWithMultiple([t.booleanLiteral(false), t.emptyStatement()]); |
| 62 | expect(generateCode(rootPath)).toBe("() => {\n return false;\n};"); |
| 63 | }); |
| 64 | |
| 65 | it("converts for loop with statement body to block", function () { |
| 66 | const rootPath = getPath("for (;;) true;"); |
| 67 | rootPath.ensureBlock(); |
| 68 | expect(generateCode(rootPath)).toBe("for (;;) {\n true;\n}"); |
| 69 | }); |
| 70 | |
| 71 | it("preserves for loop body's context", function () { |
| 72 | const rootPath = getPath("for (;;) true;"); |
| 73 | const body = rootPath.get("body"); |
| 74 | rootPath.ensureBlock(); |
| 75 | body.replaceWith(t.booleanLiteral(false)); |
| 76 | expect(generateCode(rootPath)).toBe("for (;;) {\n false;\n}"); |
| 77 | }); |
| 78 | }); |
| 79 | }); |