| 1 | import { parse } from "@babel/parser"; |
| 2 | |
| 3 | import _traverse from "../lib/index.js"; |
| 4 | import _generate from "@babel/generator"; |
| 5 | const traverse = _traverse.default || _traverse; |
| 6 | const generate = _generate.default || _generate; |
| 7 | |
| 8 | function getPath(code) { |
| 9 | const ast = parse(code); |
| 10 | let path; |
| 11 | traverse(ast, { |
| 12 | Program: function (_path) { |
| 13 | path = _path; |
| 14 | _path.stop(); |
| 15 | }, |
| 16 | }); |
| 17 | |
| 18 | return path; |
| 19 | } |
| 20 | |
| 21 | function generateCode(path) { |
| 22 | return generate(path.node).code; |
| 23 | } |
| 24 | |
| 25 | describe("removal", function () { |
| 26 | describe("ArrowFunction", function () { |
| 27 | it("remove body", function () { |
| 28 | const rootPath = getPath("x = () => b;"); |
| 29 | const path = rootPath.get("body")[0].get("expression").get("right"); |
| 30 | const body = path.get("body"); |
| 31 | body.remove(); |
| 32 | |
| 33 | expect(generateCode(rootPath)).toBe("x = () => {};"); |
| 34 | }); |
| 35 | }); |
| 36 | |
| 37 | it("remove with noScope", function () { |
| 38 | const ast = parse("a=1"); |
| 39 | traverse(ast, { |
| 40 | AssignmentExpression: function (path) { |
| 41 | path.remove(); |
| 42 | }, |
| 43 | noScope: true, |
| 44 | }); |
| 45 | |
| 46 | expect(generate(ast).code).toBe(""); |
| 47 | }); |
| 48 | |
| 49 | describe("within an IfStatement", function () { |
| 50 | it("does not make consequent null", function () { |
| 51 | const rootPath = getPath("if (x) foo(); else bar();"); |
| 52 | const ifPath = rootPath.get("body.0"); |
| 53 | ifPath.get("consequent").remove(); |
| 54 | |
| 55 | expect(ifPath.get("consequent").type).toBe("BlockStatement"); |
| 56 | }); |
| 57 | |
| 58 | it("completely removes alternate", function () { |
| 59 | const rootPath = getPath("if (x) foo(); else bar();"); |
| 60 | const ifPath = rootPath.get("body.0"); |
| 61 | ifPath.get("alternate").remove(); |
| 62 | |
| 63 | expect(ifPath.get("alternate").node).toBeNull(); |
| 64 | }); |
| 65 | }); |
| 66 | }); |