Function.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. describe("correct behavior", () => {
  2. test("constructor properties", () => {
  3. expect(Function).toHaveLength(1);
  4. expect(Function.name).toBe("Function");
  5. expect(Function.prototype).toHaveLength(0);
  6. expect(Function.prototype.name).toBe("");
  7. });
  8. test("typeof", () => {
  9. expect(typeof Function()).toBe("function");
  10. expect(typeof new Function()).toBe("function");
  11. });
  12. test("basic functionality", () => {
  13. expect(Function()()).toBeUndefined();
  14. expect(new Function()()).toBeUndefined();
  15. expect(Function("return 42")()).toBe(42);
  16. expect(new Function("return 42")()).toBe(42);
  17. expect(new Function("foo", "return foo")(42)).toBe(42);
  18. expect(new Function("foo,bar", "return foo + bar")(1, 2)).toBe(3);
  19. expect(new Function("foo", "bar", "return foo + bar")(1, 2)).toBe(3);
  20. expect(new Function("foo", "bar,baz", "return foo + bar + baz")(1, 2, 3)).toBe(6);
  21. expect(new Function("foo", "bar", "baz", "return foo + bar + baz")(1, 2, 3)).toBe(6);
  22. expect(new Function("foo", "if (foo) { return 42; } else { return 'bar'; }")(true)).toBe(
  23. 42
  24. );
  25. expect(new Function("foo", "if (foo) { return 42; } else { return 'bar'; }")(false)).toBe(
  26. "bar"
  27. );
  28. expect(new Function("return typeof Function()")()).toBe("function");
  29. expect(new Function("x", "return function (y) { return x + y };")(1)(2)).toBe(3);
  30. expect(new Function("-->")()).toBeUndefined();
  31. expect(new Function().name).toBe("anonymous");
  32. expect(new Function().toString()).toBe("function anonymous(\n) {\n\n}");
  33. });
  34. });
  35. describe("errors", () => {
  36. test("syntax error", () => {
  37. expect(() => {
  38. new Function("[");
  39. })
  40. // This might be confusing at first but keep in mind it's actually parsing
  41. // function anonymous() { [ }
  42. // Since the body, surrounded by a newline on each side, is first parsed standalone,
  43. // we report unexpected token EOF instead of }.
  44. // FIXME: The position is odd though, I'd expect `line: 2, column: 2` and `line: 3, column: 1`...
  45. // > eval("\n[") // Uncaught exception: [SyntaxError] Unexpected token Eof. Expected BracketClose (line: 2, column: 2)
  46. // > eval("\n[\n") // Uncaught exception: [SyntaxError] Unexpected token Eof. Expected BracketClose (line: 2, column: 3)
  47. .toThrowWithMessage(
  48. SyntaxError,
  49. "Unexpected token Eof. Expected BracketClose (line: 2, column: 3)"
  50. );
  51. });
  52. test("parameters and body must be valid standalone", () => {
  53. expect(() => {
  54. new Function("/*", "*/ ) {");
  55. }).toThrowWithMessage(SyntaxError, "Unterminated multi-line comment (line: 1, column: 3)");
  56. });
  57. });