JSON.stringify.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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("serialize BigInt with a toJSON property", () => {
  40. Object.defineProperty(BigInt.prototype, "toJSON", {
  41. configurable: true, // Allows deleting this property at the end of this test case.
  42. get() {
  43. "use strict";
  44. return () => typeof this;
  45. },
  46. });
  47. expect(JSON.stringify(1n)).toBe('"bigint"');
  48. delete BigInt.prototype.toJSON;
  49. });
  50. test("ignores non-enumerable properties", () => {
  51. let o = { foo: "bar" };
  52. Object.defineProperty(o, "baz", { value: "qux", enumerable: false });
  53. expect(JSON.stringify(o)).toBe('{"foo":"bar"}');
  54. });
  55. test("ignores symbol properties", () => {
  56. let o = { foo: "bar" };
  57. let sym = Symbol("baz");
  58. o[sym] = "qux";
  59. expect(JSON.stringify(o)).toBe('{"foo":"bar"}');
  60. });
  61. });
  62. describe("errors", () => {
  63. test("cannot serialize BigInt", () => {
  64. expect(() => {
  65. JSON.stringify(5n);
  66. }).toThrow(TypeError, "Cannot serialize BigInt value to JSON");
  67. });
  68. test("cannot serialize circular structures", () => {
  69. let bad1 = {};
  70. bad1.foo = bad1;
  71. let bad2 = [];
  72. bad2[5] = [[[bad2]]];
  73. let bad3a = { foo: "bar" };
  74. let bad3b = [1, 2, bad3a];
  75. bad3a.bad = bad3b;
  76. [bad1, bad2, bad3a].forEach(bad => {
  77. expect(() => {
  78. JSON.stringify(bad);
  79. }).toThrow(TypeError, "Cannot stringify circular object");
  80. });
  81. });
  82. });