Proxy.handler-get.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. });
  38. });
  39. describe("[[Get]] invariants", () => {
  40. test("returned value must match the target property value if the property is non-configurable and non-writable", () => {
  41. let o = {};
  42. Object.defineProperty(o, "foo", { value: 5, configurable: false, writable: true });
  43. Object.defineProperty(o, "bar", { value: 10, configurable: false, writable: false });
  44. let p = new Proxy(o, {
  45. get() {
  46. return 8;
  47. },
  48. });
  49. expect(p.foo).toBe(8);
  50. expect(() => {
  51. p.bar;
  52. }).toThrowWithMessage(TypeError, "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");
  53. });
  54. test("returned value must be undefined if the property is a non-configurable accessor with no getter", () => {
  55. let o = {};
  56. Object.defineProperty(o, "foo", { configurable: false, set(_) {} });
  57. let p = new Proxy(o, {
  58. get() {
  59. return 8;
  60. },
  61. });
  62. expect(() => {
  63. p.foo;
  64. }).toThrowWithMessage(TypeError, "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");
  65. })
  66. });