class-constructor.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. test("property initialization", () => {
  2. class A {
  3. constructor() {
  4. this.x = 3;
  5. }
  6. }
  7. expect(new A().x).toBe(3);
  8. });
  9. test("method initialization", () => {
  10. class A {
  11. constructor() {
  12. this.x = () => 10;
  13. }
  14. }
  15. expect(new A().x()).toBe(10);
  16. });
  17. test("initialize to class method", () => {
  18. class A {
  19. constructor() {
  20. this.x = this.method;
  21. }
  22. method() {
  23. return 10;
  24. }
  25. }
  26. expect(new A().x()).toBe(10);
  27. });
  28. test("constructor length affects class length", () => {
  29. class A {
  30. constructor() {}
  31. }
  32. expect(A).toHaveLength(0);
  33. class B {
  34. constructor(a, b, c = 2) {}
  35. }
  36. expect(B).toHaveLength(2);
  37. });
  38. test("must be invoked with 'new'", () => {
  39. class A {
  40. constructor() {}
  41. }
  42. expect(() => {
  43. A();
  44. }).toThrowWithMessage(TypeError, "Class constructor A must be called with 'new'");
  45. expect(() => {
  46. A.prototype.constructor();
  47. }).toThrowWithMessage(TypeError, "Class constructor A must be called with 'new'");
  48. });
  49. test("implicit constructor", () => {
  50. class A {}
  51. expect(new A()).toBeInstanceOf(A);
  52. });