Proxy.handler-construct.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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]) return Reflect.construct(target, [arguments[0] * 2], newTarget);
  32. return Reflect.construct(target, arguments, newTarget);
  33. },
  34. };
  35. p = new Proxy(f, handler);
  36. expect(new p(15).x).toBe(15);
  37. expect(new p(15, true).x).toBe(30);
  38. });
  39. test("trapping Reflect.construct", () => {
  40. function f(value) {
  41. this.x = value;
  42. }
  43. let p;
  44. function theNewTarget() {}
  45. const handler = {
  46. construct(target, arguments, newTarget) {
  47. expect(target).toBe(f);
  48. expect(newTarget).toBe(theNewTarget);
  49. if (arguments[1]) return Reflect.construct(target, [arguments[0] * 2], newTarget);
  50. return Reflect.construct(target, arguments, newTarget);
  51. },
  52. };
  53. p = new Proxy(f, handler);
  54. Reflect.construct(p, [15], theNewTarget);
  55. });
  56. });
  57. describe("[[Construct]] invariants", () => {
  58. test("target must have a [[Construct]] slot", () => {
  59. [{}, [], new Proxy({}, {})].forEach(item => {
  60. expect(() => {
  61. new new Proxy(item, {})();
  62. }).toThrowWithMessage(TypeError, "[object ProxyObject] is not a constructor");
  63. });
  64. });
  65. });