summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Tests/builtins/JSON/JSON.stringify.js
blob: 1e5c1743127f897a160656c9705229ac88e1b694 (plain)
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
describe("correct behavior", () => {
    test("length", () => {
        expect(JSON.stringify).toHaveLength(3);
    });

    test("basic functionality", () => {
        [
            [5, "5"],
            [undefined, undefined],
            [null, "null"],
            [NaN, "null"],
            [-NaN, "null"],
            [Infinity, "null"],
            [-Infinity, "null"],
            [true, "true"],
            [false, "false"],
            ["test", '"test"'],
            [new Number(5), "5"],
            [new Boolean(false), "false"],
            [new String("test"), '"test"'],
            [() => {}, undefined],
            [[1, 2, "foo"], '[1,2,"foo"]'],
            [{ foo: 1, bar: "baz", qux() {} }, '{"foo":1,"bar":"baz"}'],
            [
                {
                    var1: 1,
                    var2: 2,
                    toJSON(key) {
                        let o = this;
                        o.var2 = 10;
                        return o;
                    },
                },
                '{"var1":1,"var2":10}',
            ],
        ].forEach(testCase => {
            expect(JSON.stringify(testCase[0])).toEqual(testCase[1]);
        });
    });

    test("ignores non-enumerable properties", () => {
        let o = { foo: "bar" };
        Object.defineProperty(o, "baz", { value: "qux", enumerable: false });
        expect(JSON.stringify(o)).toBe('{"foo":"bar"}');
    });
});

describe("errors", () => {
    test("cannot serialize BigInt", () => {
        expect(() => {
            JSON.stringify(5n);
        }).toThrow(TypeError, "Cannot serialize BigInt value to JSON");
    });

    test("cannot serialize circular structures", () => {
        let bad1 = {};
        bad1.foo = bad1;
        let bad2 = [];
        bad2[5] = [[[bad2]]];

        let bad3a = { foo: "bar" };
        let bad3b = [1, 2, bad3a];
        bad3a.bad = bad3b;

        [bad1, bad2, bad3a].forEach(bad => {
            expect(() => {
                JSON.stringify(bad);
            }).toThrow(TypeError, "Cannot stringify circular object");
        });
    });
});