JSON.stringify.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. });
  45. describe("errors", () => {
  46. test("cannot serialize BigInt", () => {
  47. expect(() => {
  48. JSON.stringify(5n);
  49. }).toThrow(TypeError, "Cannot serialize BigInt value to JSON");
  50. });
  51. test("cannot serialize circular structures", () => {
  52. let bad1 = {};
  53. bad1.foo = bad1;
  54. let bad2 = [];
  55. bad2[5] = [[[bad2]]];
  56. let bad3a = { foo: "bar" };
  57. let bad3b = [1, 2, bad3a];
  58. bad3a.bad = bad3b;
  59. [bad1, bad2, bad3a].forEach(bad => {
  60. expect(() => {
  61. JSON.stringify(bad);
  62. }).toThrow(TypeError, "Cannot stringify circular object");
  63. });
  64. });
  65. });