Function.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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(42);
  23. expect(new Function("foo", "if (foo) { return 42; } else { return 'bar'; }")(false)).toBe(
  24. "bar"
  25. );
  26. expect(new Function("return typeof Function()")()).toBe("function");
  27. expect(new Function("x", "return function (y) { return x + y };")(1)(2)).toBe(3);
  28. expect(new Function().name).toBe("anonymous");
  29. expect(new Function().toString()).toBe("function anonymous() {\n ???\n}");
  30. });
  31. });
  32. describe("errors", () => {
  33. test("syntax error", () => {
  34. expect(() => {
  35. new Function("[");
  36. })
  37. // This might be confusing at first but keep in mind it's actually parsing
  38. // function anonymous() { [ }
  39. // This is in line with what other engines are reporting.
  40. .toThrowWithMessage(
  41. SyntaxError,
  42. "Unexpected token CurlyClose. Expected BracketClose (line: 1, column: 26)"
  43. );
  44. });
  45. });