import { describe, expect, test } from "bun:test"; import TWUIEJSON from "./ejson"; describe("TWUIEJSON.parse", () => { test("parses valid JSON string", () => { expect(TWUIEJSON.parse('{"key":"value"}')).toEqual({ key: "value" }); }); test("parses valid JSON array string", () => { expect(TWUIEJSON.parse("[1,2,3]")).toEqual([1, 2, 3]); }); test("returns undefined for null input", () => { expect(TWUIEJSON.parse(null)).toBeUndefined(); }); test("returns undefined for undefined input (0 is falsy)", () => { expect(TWUIEJSON.parse(0)).toBeUndefined(); }); test("returns undefined for number input", () => { expect(TWUIEJSON.parse(42)).toBeUndefined(); }); test("returns undefined for empty string", () => { expect(TWUIEJSON.parse("")).toBeUndefined(); }); test("returns object as-is for object input", () => { const obj = { a: 1 }; expect(TWUIEJSON.parse(obj as any)).toBe(obj); }); test("returns undefined for invalid JSON string", () => { expect(TWUIEJSON.parse("not json")).toBeUndefined(); }); test("returns undefined for malformed JSON", () => { expect(TWUIEJSON.parse("{invalid}")).toBeUndefined(); }); test("parses nested JSON", () => { const result = TWUIEJSON.parse('{"outer":{"inner":42}}'); expect(result).toEqual({ outer: { inner: 42 } }); }); test("supports reviver function", () => { const result = TWUIEJSON.parse('{"a":"1","b":"2"}', (_key, value) => typeof value === "string" && !isNaN(Number(value)) ? Number(value) : value ); expect(result).toEqual({ a: 1, b: 2 }); }); test("parses boolean JSON values", () => { expect(TWUIEJSON.parse("true") as unknown).toBe(true); expect(TWUIEJSON.parse("false") as unknown).toBe(false); }); test("parses null JSON value", () => { expect(TWUIEJSON.parse("null") as unknown).toBeNull(); }); }); describe("TWUIEJSON.stringify", () => { test("stringifies an object", () => { expect(TWUIEJSON.stringify({ key: "value" })).toBe('{"key":"value"}'); }); test("stringifies an array", () => { expect(TWUIEJSON.stringify([1, 2, 3])).toBe("[1,2,3]"); }); test("returns undefined for circular reference", () => { const obj: any = { a: 1 }; obj.self = obj; expect(TWUIEJSON.stringify(obj)).toBeUndefined(); }); test("supports replacer function", () => { const result = TWUIEJSON.stringify({ a: 1, b: 2 }, (_key, value) => typeof value === "number" ? value * 2 : value ); expect(result).toBe('{"a":2,"b":4}'); }); test("supports space parameter for formatting", () => { const result = TWUIEJSON.stringify({ a: 1 }, null, 2); expect(result).toContain('\n'); expect(result).toContain(' '); }); test("stringifies primitive values", () => { expect(TWUIEJSON.stringify("hello")).toBe('"hello"'); expect(TWUIEJSON.stringify(42)).toBe("42"); expect(TWUIEJSON.stringify(null)).toBe("null"); }); });