Proxy.handler-get.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. describe("[[Get]] trap normal behavior", () => {
  2. test("forwarding when not defined in handler", () => {
  3. expect(new Proxy({}, { get: undefined }).foo).toBeUndefined();
  4. expect(new Proxy({}, { get: null }).foo).toBeUndefined();
  5. expect(new Proxy({}, {}).foo).toBeUndefined();
  6. });
  7. test("correct arguments supplied to trap", () => {
  8. let o = {};
  9. let p = new Proxy(o, {
  10. get(target, property, receiver) {
  11. expect(target).toBe(o);
  12. expect(property).toBe("foo");
  13. expect(receiver).toBe(p);
  14. },
  15. });
  16. p.foo;
  17. });
  18. test("conditional return", () => {
  19. let o = { foo: 1 };
  20. let p = new Proxy(o, {
  21. get(target, property, receiver) {
  22. if (property === "bar") {
  23. return 2;
  24. } else if (property === "baz") {
  25. return receiver.qux;
  26. } else if (property === "qux") {
  27. return 3;
  28. }
  29. return target[property];
  30. },
  31. });
  32. expect(p.foo).toBe(1);
  33. expect(p.bar).toBe(2);
  34. expect(p.baz).toBe(3);
  35. expect(p.qux).toBe(3);
  36. expect(p.test).toBeUndefined();
  37. expect(p[Symbol.hasInstance]).toBeUndefined();
  38. });
  39. });
  40. describe("[[Get]] invariants", () => {
  41. test("returned value must match the target property value if the property is non-configurable and non-writable", () => {
  42. let o = {};
  43. Object.defineProperty(o, "foo", { value: 5, configurable: false, writable: true });
  44. Object.defineProperty(o, "bar", { value: 10, configurable: false, writable: false });
  45. let p = new Proxy(o, {
  46. get() {
  47. return 8;
  48. },
  49. });
  50. expect(p.foo).toBe(8);
  51. expect(() => {
  52. p.bar;
  53. }).toThrowWithMessage(
  54. TypeError,
  55. "Proxy handler's get trap violates invariant: the returned value must match the value on the target if the property exists on the target as a non-writable, non-configurable own data property"
  56. );
  57. });
  58. test("returned value must be undefined if the property is a non-configurable accessor with no getter", () => {
  59. let o = {};
  60. Object.defineProperty(o, "foo", { configurable: false, set(_) {} });
  61. let p = new Proxy(o, {
  62. get() {
  63. return 8;
  64. },
  65. });
  66. expect(() => {
  67. p.foo;
  68. }).toThrowWithMessage(
  69. TypeError,
  70. "Proxy handler's get trap violates invariant: the returned value must be undefined if the property exists on the target as a non-configurable accessor property with an undefined get attribute"
  71. );
  72. });
  73. });