JSON.parse.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. test("basic functionality", () => {
  2. expect(JSON.parse).toHaveLength(2);
  3. const properties = [
  4. ["5", 5],
  5. ["null", null],
  6. ["true", true],
  7. ["false", false],
  8. ['"test"', "test"],
  9. ['[1,2,"foo"]', [1, 2, "foo"]],
  10. ['{"foo":1,"bar":"baz"}', { foo: 1, bar: "baz" }],
  11. ];
  12. properties.forEach(testCase => {
  13. expect(JSON.parse(testCase[0])).toEqual(testCase[1]);
  14. });
  15. });
  16. test("syntax errors", () => {
  17. [
  18. undefined,
  19. NaN,
  20. -NaN,
  21. Infinity,
  22. -Infinity,
  23. '{ "foo" }',
  24. '{ foo: "bar" }',
  25. "[1,2,3,]",
  26. "[1,2,3, ]",
  27. '{ "foo": "bar",}',
  28. '{ "foo": "bar", }',
  29. "",
  30. ].forEach(test => {
  31. expect(() => {
  32. JSON.parse(test);
  33. }).toThrow(SyntaxError);
  34. });
  35. });
  36. test("negative zero", () => {
  37. ["-0", " \n-0", "-0 \t", "\n\t -0\n ", "-0.0"].forEach(testCase => {
  38. expect(JSON.parse(testCase)).toEqual(-0.0);
  39. });
  40. expect(JSON.parse(-0)).toEqual(0);
  41. });
  42. // The underlying parser resolves decimal numbers by storing the decimal portion in an integer
  43. // This test handles a regression where the decimal portion was only using a u32 vs. u64
  44. // and would fail to parse.
  45. test("long decimal parse", () => {
  46. expect(JSON.parse("1644452550.6489999294281")).toEqual(1644452550.6489999294281);
  47. });
  48. test("does not truncate large integers", () => {
  49. expect(JSON.parse("1234567890123")).toEqual(1234567890123);
  50. expect(JSON.parse("4294967295")).toEqual(4294967295);
  51. expect(JSON.parse("4294967296")).toEqual(4294967296);
  52. expect(JSON.parse("4294967297")).toEqual(4294967297);
  53. expect(JSON.parse("4294967298")).toEqual(4294967298);
  54. expect(JSON.parse("2147483647")).toEqual(2147483647);
  55. expect(JSON.parse("2147483648")).toEqual(2147483648);
  56. expect(JSON.parse("2147483649")).toEqual(2147483649);
  57. expect(JSON.parse("2147483650")).toEqual(2147483650);
  58. expect(JSON.parse("9007199254740991")).toEqual(9007199254740991);
  59. expect(JSON.parse("9007199254740992")).toEqual(9007199254740992);
  60. expect(JSON.parse("9007199254740993")).toEqual(9007199254740993);
  61. expect(JSON.parse("9007199254740994")).toEqual(9007199254740994);
  62. expect(JSON.parse("9008199254740994")).toEqual(9008199254740994);
  63. expect(JSON.parse("18446744073709551615")).toEqual(18446744073709551615);
  64. expect(JSON.parse("18446744073709551616")).toEqual(18446744073709551616);
  65. expect(JSON.parse("18446744073709551617")).toEqual(18446744073709551617);
  66. });