Proxy.handler-construct.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. describe("[[Construct]] trap normal behavior", () => {
  2. test("forwarding when not defined in handler", () => {
  3. let p = new Proxy(
  4. function () {
  5. this.x = 5;
  6. },
  7. { construct: null }
  8. );
  9. expect(new p().x).toBe(5);
  10. p = new Proxy(
  11. function () {
  12. this.x = 5;
  13. },
  14. { construct: undefined }
  15. );
  16. expect(new p().x).toBe(5);
  17. p = new Proxy(function () {
  18. this.x = 5;
  19. }, {});
  20. expect(new p().x).toBe(5);
  21. });
  22. test("trapping 'new'", () => {
  23. function f(value) {
  24. this.x = value;
  25. }
  26. let p;
  27. const handler = {
  28. construct(target, arguments_, newTarget) {
  29. expect(target).toBe(f);
  30. expect(newTarget).toBe(p);
  31. if (arguments_[1]) {
  32. return Reflect.construct(target, [arguments_[0] * 2], newTarget);
  33. }
  34. return Reflect.construct(target, arguments_, newTarget);
  35. },
  36. };
  37. p = new Proxy(f, handler);
  38. expect(new p(15).x).toBe(15);
  39. expect(new p(15, true).x).toBe(30);
  40. });
  41. test("trapping Reflect.construct", () => {
  42. function f(value) {
  43. this.x = value;
  44. }
  45. let p;
  46. function theNewTarget() {}
  47. const handler = {
  48. construct(target, arguments_, newTarget) {
  49. expect(target).toBe(f);
  50. expect(newTarget).toBe(theNewTarget);
  51. if (arguments_[1]) {
  52. return Reflect.construct(target, [arguments_[0] * 2], newTarget);
  53. }
  54. return Reflect.construct(target, arguments_, newTarget);
  55. },
  56. };
  57. p = new Proxy(f, handler);
  58. Reflect.construct(p, [15], theNewTarget);
  59. });
  60. });
  61. describe("[[Construct]] invariants", () => {
  62. test("target must have a [[Construct]] slot", () => {
  63. [{}, [], new Proxy({}, {})].forEach(item => {
  64. expect(() => {
  65. new new Proxy(item, {})();
  66. }).toThrowWithMessage(TypeError, "[object ProxyObject] is not a constructor");
  67. });
  68. });
  69. });