Proxy.handler-has.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. describe("[[Has]] trap normal behavior", () => {
  2. test("forwarding when not defined in handler", () => {
  3. expect("foo" in new Proxy({}, { has: null })).toBeFalse();
  4. expect("foo" in new Proxy({}, { has: undefined })).toBeFalse();
  5. expect("foo" in new Proxy({}, {})).toBeFalse();
  6. });
  7. test("correct arguments supplied to trap", () => {
  8. let o = {};
  9. let p = new Proxy(o, {
  10. has(target, prop) {
  11. expect(target).toBe(o);
  12. expect(prop).toBe("foo");
  13. return true;
  14. },
  15. });
  16. "foo" in p;
  17. });
  18. test("conditional return", () => {
  19. let o = {};
  20. let p = new Proxy(o, {
  21. has(target, prop) {
  22. if (target.checkedFoo) return true;
  23. if (prop === "foo") target.checkedFoo = true;
  24. return false;
  25. },
  26. });
  27. expect("foo" in p).toBeFalse();
  28. expect("foo" in p).toBeTrue();
  29. });
  30. });
  31. describe("[[Has]] invariants", () => {
  32. test("cannot return false if the property exists and is non-configurable", () => {
  33. let o = {};
  34. Object.defineProperty(o, "foo", { configurable: false });
  35. p = new Proxy(o, {
  36. has() {
  37. return false;
  38. },
  39. });
  40. expect(() => {
  41. "foo" in p;
  42. }).toThrowWithMessage(
  43. TypeError,
  44. "Proxy handler's has trap violates invariant: a property cannot be reported as non-existent if it exists on the target as a non-configurable property"
  45. );
  46. });
  47. test("cannot return false if the property exists and the target is non-extensible", () => {
  48. let o = {};
  49. Object.defineProperty(o, "foo", { value: 10, configurable: true });
  50. let p = new Proxy(o, {
  51. has() {
  52. return false;
  53. },
  54. });
  55. Object.preventExtensions(o);
  56. expect(() => {
  57. "foo" in p;
  58. }).toThrowWithMessage(
  59. TypeError,
  60. "Proxy handler's has trap violates invariant: a property cannot be reported as non-existent if it exists on the target and the target is non-extensible"
  61. );
  62. });
  63. });