Function.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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}");
  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. // This is in line with what other engines are reporting.
  43. .toThrowWithMessage(
  44. SyntaxError,
  45. "Unexpected token CurlyClose. Expected BracketClose (line: 4, column: 1)"
  46. );
  47. });
  48. });