eval-basic.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. test("basic eval() functionality", () => {
  2. expect(eval("1 + 2")).toBe(3);
  3. function foo(a) {
  4. var x = 5;
  5. eval("x += a");
  6. return x;
  7. }
  8. expect(foo(7)).toBe(12);
  9. });
  10. test("returns value of last value-producing statement", () => {
  11. // See https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
  12. expect(eval("")).toBeUndefined();
  13. expect(eval("1;;;;;")).toBe(1);
  14. expect(eval("1;{}")).toBe(1);
  15. expect(eval("1;var a;")).toBe(1);
  16. });
  17. test("syntax error", () => {
  18. expect(() => {
  19. eval("{");
  20. }).toThrowWithMessage(
  21. SyntaxError,
  22. "Unexpected token Eof. Expected CurlyClose (line: 1, column: 2)"
  23. );
  24. });
  25. test("returns 1st argument unless 1st argument is a string", () => {
  26. var stringObject = new String("1 + 2");
  27. expect(eval(stringObject)).toBe(stringObject);
  28. });
  29. // These eval scope tests use function expressions due to bug #8198
  30. var testValue = "outer";
  31. test("eval only touches locals if direct use", function () {
  32. var testValue = "inner";
  33. expect(globalThis.eval("testValue")).toEqual("outer");
  34. });
  35. test("alias to eval works as a global eval", function () {
  36. var testValue = "inner";
  37. var eval1 = globalThis.eval;
  38. expect(eval1("testValue")).toEqual("outer");
  39. });
  40. test("eval evaluates all args", function () {
  41. var i = 0;
  42. expect(eval("testValue", i++, i++, i++)).toEqual("outer");
  43. expect(i).toEqual(3);
  44. });
  45. test("eval tests for exceptions", function () {
  46. var i = 0;
  47. expect(function () {
  48. eval("testValue", i++, i++, j, i++);
  49. }).toThrowWithMessage(ReferenceError, "'j' is not defined");
  50. expect(i).toEqual(2);
  51. });
  52. test("direct eval inherits non-strict evaluation", function () {
  53. expect(eval("01")).toEqual(1);
  54. });
  55. test("direct eval inherits strict evaluation", function () {
  56. "use strict";
  57. expect(() => {
  58. eval("01");
  59. }).toThrowWithMessage(SyntaxError, "Unprefixed octal number not allowed in strict mode");
  60. });
  61. test("global eval evaluates as non-strict", function () {
  62. "use strict";
  63. expect(globalThis.eval("01"));
  64. });