/
cloning.js
75 lines (67 loc) 路 2.38 KB
/
cloning.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
import * as t from "../lib";
import { parse } from "@babel/parser";
describe("cloneNode", function() {
it("should handle undefined", function() {
const node = undefined;
const cloned = t.cloneNode(node);
expect(cloned).toBeUndefined();
});
it("should handle null", function() {
const node = null;
const cloned = t.cloneNode(node);
expect(cloned).toBeNull();
});
it("should handle simple cases", function() {
const node = t.identifier("a");
const cloned = t.cloneNode(node);
expect(node).not.toBe(cloned);
expect(t.isNodesEquivalent(node, cloned)).toBe(true);
});
it("should handle full programs", function() {
const file = parse("1 + 1");
const cloned = t.cloneNode(file);
expect(file).not.toBe(cloned);
expect(file.program.body[0].expression.right).not.toBe(
cloned.program.body[0].expression.right,
);
expect(file.program.body[0].expression.left).not.toBe(
cloned.program.body[0].expression.left,
);
expect(t.isNodesEquivalent(file, cloned)).toBe(true);
});
it("should handle complex programs", function() {
const program = "'use strict'; function lol() { wow();return 1; }";
const node = parse(program);
const cloned = t.cloneNode(node);
expect(node).not.toBe(cloned);
expect(t.isNodesEquivalent(node, cloned)).toBe(true);
});
it("should handle missing array element", function() {
const node = parse("[,0]");
const cloned = t.cloneNode(node);
expect(node).not.toBe(cloned);
expect(t.isNodesEquivalent(node, cloned)).toBe(true);
});
it("should support shallow cloning", function() {
const node = t.memberExpression(t.identifier("foo"), t.identifier("bar"));
const cloned = t.cloneNode(node, /* deep */ false);
expect(node).not.toBe(cloned);
expect(node.object).toBe(cloned.object);
expect(node.property).toBe(cloned.property);
});
it("should preserve type annotations", function() {
const node = t.variableDeclaration("let", [
t.variableDeclarator({
...t.identifier("value"),
typeAnnotation: t.anyTypeAnnotation(),
}),
]);
const cloned = t.cloneNode(node, /* deep */ true);
expect(cloned.declarations[0].id.typeAnnotation).toEqual(
node.declarations[0].id.typeAnnotation,
);
expect(cloned.declarations[0].id.typeAnnotation).not.toBe(
node.declarations[0].id.typeAnnotation,
);
});
});