cloning.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import * as t from "../lib";
  2. import { parse } from "@babel/parser";
  3. describe("cloneNode", function() {
  4. it("should handle undefined", function() {
  5. const node = undefined;
  6. const cloned = t.cloneNode(node);
  7. expect(cloned).toBeUndefined();
  8. });
  9. it("should handle null", function() {
  10. const node = null;
  11. const cloned = t.cloneNode(node);
  12. expect(cloned).toBeNull();
  13. });
  14. it("should handle simple cases", function() {
  15. const node = t.identifier("a");
  16. const cloned = t.cloneNode(node);
  17. expect(node).not.toBe(cloned);
  18. expect(t.isNodesEquivalent(node, cloned)).toBe(true);
  19. });
  20. it("should handle full programs", function() {
  21. const file = parse("1 + 1");
  22. const cloned = t.cloneNode(file);
  23. expect(file).not.toBe(cloned);
  24. expect(file.program.body[0].expression.right).not.toBe(
  25. cloned.program.body[0].expression.right,
  26. );
  27. expect(file.program.body[0].expression.left).not.toBe(
  28. cloned.program.body[0].expression.left,
  29. );
  30. expect(t.isNodesEquivalent(file, cloned)).toBe(true);
  31. });
  32. it("should handle complex programs", function() {
  33. const program = "'use strict'; function lol() { wow();return 1; }";
  34. const node = parse(program);
  35. const cloned = t.cloneNode(node);
  36. expect(node).not.toBe(cloned);
  37. expect(t.isNodesEquivalent(node, cloned)).toBe(true);
  38. });
  39. it("should handle missing array element", function() {
  40. const node = parse("[,0]");
  41. const cloned = t.cloneNode(node);
  42. expect(node).not.toBe(cloned);
  43. expect(t.isNodesEquivalent(node, cloned)).toBe(true);
  44. });
  45. it("should support shallow cloning", function() {
  46. const node = t.memberExpression(t.identifier("foo"), t.identifier("bar"));
  47. const cloned = t.cloneNode(node, /* deep */ false);
  48. expect(node).not.toBe(cloned);
  49. expect(node.object).toBe(cloned.object);
  50. expect(node.property).toBe(cloned.property);
  51. });
  52. });