Function.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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().name).toBe("anonymous");
  31. expect(new Function().toString()).toBe("function anonymous() {\n ???\n}");
  32. });
  33. });
  34. describe("errors", () => {
  35. test("syntax error", () => {
  36. expect(() => {
  37. new Function("[");
  38. })
  39. // This might be confusing at first but keep in mind it's actually parsing
  40. // function anonymous() { [ }
  41. // This is in line with what other engines are reporting.
  42. .toThrowWithMessage(
  43. SyntaxError,
  44. "Unexpected token CurlyClose. Expected BracketClose (line: 1, column: 26)"
  45. );
  46. });
  47. });