JSON.stringify.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. describe("correct behavior", () => {
  2. test("length", () => {
  3. expect(JSON.stringify).toHaveLength(3);
  4. });
  5. test("basic functionality", () => {
  6. [
  7. [5, "5"],
  8. [undefined, undefined],
  9. [null, "null"],
  10. [NaN, "null"],
  11. [-NaN, "null"],
  12. [Infinity, "null"],
  13. [-Infinity, "null"],
  14. [true, "true"],
  15. [false, "false"],
  16. ["test", '"test"'],
  17. [new Number(5), "5"],
  18. [new Boolean(false), "false"],
  19. [new String("test"), '"test"'],
  20. [() => {}, undefined],
  21. [[1, 2, "foo"], '[1,2,"foo"]'],
  22. [{ foo: 1, bar: "baz", qux() {} }, '{"foo":1,"bar":"baz"}'],
  23. [
  24. {
  25. var1: 1,
  26. var2: 2,
  27. toJSON(key) {
  28. let o = this;
  29. o.var2 = 10;
  30. return o;
  31. },
  32. },
  33. '{"var1":1,"var2":10}',
  34. ],
  35. ].forEach(testCase => {
  36. expect(JSON.stringify(testCase[0])).toEqual(testCase[1]);
  37. });
  38. });
  39. test("ignores non-enumerable properties", () => {
  40. let o = { foo: "bar" };
  41. Object.defineProperty(o, "baz", { value: "qux", enumerable: false });
  42. expect(JSON.stringify(o)).toBe('{"foo":"bar"}');
  43. });
  44. test("ignores symbol properties", () => {
  45. let o = { foo: "bar" };
  46. let sym = Symbol("baz");
  47. o[sym] = "qux";
  48. expect(JSON.stringify(o)).toBe('{"foo":"bar"}');
  49. });
  50. });
  51. describe("errors", () => {
  52. test("cannot serialize BigInt", () => {
  53. expect(() => {
  54. JSON.stringify(5n);
  55. }).toThrow(TypeError, "Cannot serialize BigInt value to JSON");
  56. });
  57. test("cannot serialize circular structures", () => {
  58. let bad1 = {};
  59. bad1.foo = bad1;
  60. let bad2 = [];
  61. bad2[5] = [[[bad2]]];
  62. let bad3a = { foo: "bar" };
  63. let bad3b = [1, 2, bad3a];
  64. bad3a.bad = bad3b;
  65. [bad1, bad2, bad3a].forEach(bad => {
  66. expect(() => {
  67. JSON.stringify(bad);
  68. }).toThrow(TypeError, "Cannot stringify circular object");
  69. });
  70. });
  71. });