class-public-fields.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. test("basic functionality", () => {
  2. class A {
  3. number = 3;
  4. string = "foo";
  5. uninitialized;
  6. }
  7. const a = new A();
  8. expect(a.number).toBe(3);
  9. expect(a.string).toBe("foo");
  10. expect(a.uninitialized).toBeUndefined();
  11. });
  12. test("extended name syntax", () => {
  13. class A {
  14. "field with space" = 1;
  15. 12 = "twelve";
  16. [`he${"llo"}`] = 3;
  17. }
  18. const a = new A();
  19. expect(a["field with space"]).toBe(1);
  20. expect(a[12]).toBe("twelve");
  21. expect(a.hello).toBe(3);
  22. });
  23. test("initializer has correct this value", () => {
  24. class A {
  25. this_val = this;
  26. this_name = this.this_val;
  27. }
  28. const a = new A();
  29. expect(a.this_val).toBe(a);
  30. expect(a.this_name).toBe(a);
  31. });
  32. test("static fields", () => {
  33. class A {
  34. static simple = 1;
  35. simple = 2;
  36. static "with space" = 3;
  37. static 24 = "two dozen";
  38. static [`he${"llo"}`] = "friends";
  39. static this_val = this;
  40. static this_name = this.name;
  41. static this_val2 = this.this_val;
  42. }
  43. expect(A.simple).toBe(1);
  44. expect(A["with space"]).toBe(3);
  45. expect(A[24]).toBe("two dozen");
  46. expect(A.hello).toBe("friends");
  47. expect(A.this_val).toBe(A);
  48. expect(A.this_name).toBe("A");
  49. expect(A.this_val2).toBe(A);
  50. const a = new A();
  51. expect(a.simple).toBe(2);
  52. });
  53. test("with super class", () => {
  54. class A {
  55. super_field = 3;
  56. }
  57. class B extends A {
  58. references_super_field = super.super_field;
  59. arrow_ref_super = () => (super.super_field = 4);
  60. }
  61. const b = new B();
  62. expect(b.super_field).toBe(3);
  63. expect(b.references_super_field).toBeUndefined();
  64. b.arrow_ref_super();
  65. expect(b.super_field).toBe(4);
  66. });
  67. describe("class fields with a 'special' name", () => {
  68. test("static", () => {
  69. class A {
  70. static;
  71. }
  72. expect("static" in new A()).toBeTrue();
  73. class B {
  74. static;
  75. }
  76. expect("static" in new B()).toBeTrue();
  77. class C {
  78. static a;
  79. }
  80. expect("static" in new C()).toBeFalse();
  81. expect("a" in new C()).toBeFalse();
  82. expect("a" in C).toBeTrue();
  83. expect("static" in C).toBeFalse();
  84. });
  85. test("async", () => {
  86. class A {
  87. async;
  88. }
  89. expect("async" in new A()).toBeTrue();
  90. class B {
  91. async;
  92. }
  93. expect("async" in new B()).toBeTrue();
  94. class C {
  95. async;
  96. a;
  97. }
  98. expect("async" in new C()).toBeTrue();
  99. expect("a" in new C()).toBeTrue();
  100. });
  101. });