class-methods.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. test("basic functionality", () => {
  2. class A {
  3. number() {
  4. return 2;
  5. }
  6. string() {
  7. return "foo";
  8. }
  9. }
  10. const a = new A();
  11. expect(a.number()).toBe(2);
  12. expect(a.string()).toBe("foo");
  13. });
  14. test("length", () => {
  15. class A {
  16. method1() {}
  17. method2(a, b, c, d) {}
  18. method3(a, b, ...c) {}
  19. }
  20. const a = new A();
  21. expect(a.method1).toHaveLength(0);
  22. expect(a.method2).toHaveLength(4);
  23. expect(a.method3).toHaveLength(2);
  24. });
  25. test("extended name syntax", () => {
  26. class A {
  27. "method with space"() {
  28. return 1;
  29. }
  30. 12() {
  31. return 2;
  32. }
  33. [`he${"llo"}`]() {
  34. return 3;
  35. }
  36. }
  37. const a = new A();
  38. expect(a["method with space"]()).toBe(1);
  39. expect(a[12]()).toBe(2);
  40. expect(a.hello()).toBe(3);
  41. });
  42. test("method named 'async'", () => {
  43. class A {
  44. async() {
  45. return "function named async";
  46. }
  47. }
  48. const a = new A();
  49. expect("async" in a).toBeTrue();
  50. expect(a.async()).toBe("function named async");
  51. });
  52. test("can call other private methods from methods", () => {
  53. class A {
  54. #a() {
  55. return 1;
  56. }
  57. async #b() {
  58. return 2;
  59. }
  60. syncA() {
  61. return this.#a();
  62. }
  63. async asyncA() {
  64. return this.#a();
  65. }
  66. syncB() {
  67. return this.#b();
  68. }
  69. async asyncB() {
  70. return this.#b();
  71. }
  72. }
  73. var called = false;
  74. async function check() {
  75. called = true;
  76. const a = new A();
  77. expect(a.syncA()).toBe(1);
  78. expect(await a.asyncA()).toBe(1);
  79. expect(await a.syncB()).toBe(2);
  80. expect(await a.asyncB()).toBe(2);
  81. return 3;
  82. }
  83. var error = null;
  84. var failed = false;
  85. check().then(
  86. value => {
  87. expect(called).toBeTrue();
  88. expect(value).toBe(3);
  89. },
  90. thrownError => {
  91. failed = true;
  92. error = thrownError;
  93. }
  94. );
  95. runQueuedPromiseJobs();
  96. expect(called).toBeTrue();
  97. if (failed) throw error;
  98. expect(failed).toBeFalse();
  99. });