class-setters.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. test("basic functionality", () => {
  2. class A {
  3. get x() {
  4. return this._x;
  5. }
  6. set x(value) {
  7. this._x = value * 2;
  8. }
  9. }
  10. expect(A.x).toBeUndefined();
  11. expect(A).not.toHaveProperty("_x");
  12. const a = new A();
  13. expect(a.x).toBeUndefined();
  14. expect(a).not.toHaveProperty("_x");
  15. a.x = 3;
  16. expect(a.x).toBe(6);
  17. expect(a).toHaveProperty("_x", 6);
  18. });
  19. test("name", () => {
  20. class A {
  21. set x(v) {}
  22. }
  23. const d = Object.getOwnPropertyDescriptor(A.prototype, "x");
  24. expect(d.set.name).toBe("set x");
  25. });
  26. test("extended name syntax", () => {
  27. const s = Symbol("foo");
  28. class A {
  29. set "method with space"(value) {
  30. this.a = value;
  31. }
  32. set 12(value) {
  33. this.b = value;
  34. }
  35. set [`he${"llo"}`](value) {
  36. this.c = value;
  37. }
  38. set [s](value) {
  39. this.d = value;
  40. }
  41. }
  42. const a = new A();
  43. a["method with space"] = 1;
  44. a[12] = 2;
  45. a.hello = 3;
  46. a[s] = 4;
  47. expect(a.a).toBe(1);
  48. expect(a.b).toBe(2);
  49. expect(a.c).toBe(3);
  50. expect(a.d).toBe(4);
  51. });
  52. test("inherited setter", () => {
  53. class Parent {
  54. get x() {
  55. return this._x;
  56. }
  57. set x(value) {
  58. this._x = value * 2;
  59. }
  60. }
  61. class Child extends Parent {}
  62. const c = new Child();
  63. expect(c.x).toBeUndefined();
  64. c.x = 10;
  65. expect(c.x).toBe(20);
  66. });
  67. test("inherited static setter overriding", () => {
  68. class Parent {
  69. get x() {
  70. return this._x;
  71. }
  72. set x(value) {
  73. this._x = value * 2;
  74. }
  75. }
  76. class Child extends Parent {
  77. get x() {
  78. return this._x;
  79. }
  80. set x(value) {
  81. this._x = value * 3;
  82. }
  83. }
  84. const c = new Child();
  85. expect(c.x).toBeUndefined();
  86. c.x = 10;
  87. expect(c.x).toBe(30);
  88. });