function-name.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. test("basic functionality", () => {
  2. expect(function () {}.name).toBe("");
  3. function bar() {}
  4. expect(bar.name).toBe("bar");
  5. expect((bar.name = "baz")).toBe("baz");
  6. expect(bar.name).toBe("bar");
  7. });
  8. test("function assigned to variable", () => {
  9. let foo = function () {};
  10. expect(foo.name).toBe("foo");
  11. expect((foo.name = "bar")).toBe("bar");
  12. expect(foo.name).toBe("foo");
  13. let a, b;
  14. a = b = function () {};
  15. expect(a.name).toBe("b");
  16. expect(b.name).toBe("b");
  17. });
  18. test("functions in array assigned to variable", () => {
  19. const arr = [function () {}, function () {}, function () {}];
  20. expect(arr[0].name).toBe("");
  21. expect(arr[1].name).toBe("");
  22. expect(arr[2].name).toBe("");
  23. });
  24. test("functions in objects", () => {
  25. let f;
  26. let o = { a: function () {} };
  27. expect(o.a.name).toBe("a");
  28. f = o.a;
  29. expect(f.name).toBe("a");
  30. expect(o.a.name).toBe("a");
  31. o = { ...o, b: f };
  32. expect(o.a.name).toBe("a");
  33. expect(o.b.name).toBe("a");
  34. // Member expressions do not get named.
  35. o.c = function () {};
  36. expect(o.c.name).toBe("");
  37. });
  38. test("names of native functions", () => {
  39. expect(console.debug.name).toBe("debug");
  40. expect((console.debug.name = "warn")).toBe("warn");
  41. expect(console.debug.name).toBe("debug");
  42. });
  43. describe("some anonymous functions get renamed", () => {
  44. test("direct assignment does name new function expression", () => {
  45. // prettier-ignore
  46. let f1 = (function () {});
  47. expect(f1.name).toBe("f1");
  48. let f2 = false;
  49. f2 ||= function () {};
  50. expect(f2.name).toBe("f2");
  51. });
  52. test("assignment from variable does not name", () => {
  53. const f1 = function () {};
  54. let f3 = f1;
  55. expect(f3.name).toBe("f1");
  56. });
  57. test("assignment via expression does not name", () => {
  58. let f4 = false || function () {};
  59. expect(f4.name).toBe("");
  60. });
  61. });