-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathdeepClone.test.ts
More file actions
67 lines (51 loc) · 1.8 KB
/
deepClone.test.ts
File metadata and controls
67 lines (51 loc) · 1.8 KB
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
import { describe, expect, it, afterEach } from "vitest";
import { deepClone } from "./deepClone";
describe("deepClone", () => {
const originalStructuredClone = (globalThis as any).structuredClone;
afterEach(() => {
(globalThis as any).structuredClone = originalStructuredClone;
});
it("deep clones plain objects when structuredClone is missing", () => {
(globalThis as any).structuredClone = undefined;
const value = { a: 1, b: { c: 2 }, d: [1, { e: 3 }] };
const cloned = deepClone(value);
expect(cloned).toEqual(value);
expect(cloned).not.toBe(value);
expect(cloned.b).not.toBe(value.b);
expect(cloned.d).not.toBe(value.d);
expect(cloned.d[1]).not.toBe(value.d[1]);
});
it("handles circular references in the fallback clone", () => {
(globalThis as any).structuredClone = undefined;
const value: { self?: unknown } = {};
value.self = value;
const cloned = deepClone(value) as typeof value;
expect(cloned).not.toBe(value);
expect(cloned.self).toBe(cloned);
});
it("falls back if structuredClone throws", () => {
(globalThis as any).structuredClone = () => {
throw new Error("boom");
};
const value = { a: 1, b: { c: 2 } };
const cloned = deepClone(value);
expect(cloned).toEqual(value);
expect(cloned).not.toBe(value);
expect(cloned.b).not.toBe(value.b);
});
it("clones class instances without mutating the original", () => {
(globalThis as any).structuredClone = undefined;
class Example {
public nested: { value: number };
constructor(value: number) {
this.nested = { value };
}
}
const instance = new Example(123);
const cloned = deepClone(instance);
expect(cloned).toBeInstanceOf(Example);
expect(cloned).not.toBe(instance);
expect(cloned.nested).toEqual(instance.nested);
expect(cloned.nested).not.toBe(instance.nested);
});
});