Proxy.handler-has.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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("correct arguments passed to trap even for number", () => {
  19. let o = {};
  20. let p = new Proxy(o, {
  21. has(target, prop) {
  22. expect(target).toBe(o);
  23. expect(prop).toBe("1");
  24. return true;
  25. },
  26. });
  27. 1 in p;
  28. });
  29. test("conditional return", () => {
  30. let o = {};
  31. let p = new Proxy(o, {
  32. has(target, prop) {
  33. if (target.checkedFoo) return true;
  34. if (prop === "foo") target.checkedFoo = true;
  35. return false;
  36. },
  37. });
  38. expect("foo" in p).toBeFalse();
  39. expect("foo" in p).toBeTrue();
  40. });
  41. });
  42. describe("[[Has]] invariants", () => {
  43. test("cannot return false if the property exists and is non-configurable", () => {
  44. let o = {};
  45. Object.defineProperty(o, "foo", { configurable: false });
  46. p = new Proxy(o, {
  47. has() {
  48. return false;
  49. },
  50. });
  51. expect(() => {
  52. "foo" in p;
  53. }).toThrowWithMessage(
  54. TypeError,
  55. "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"
  56. );
  57. });
  58. test("cannot return false if the property exists and the target is non-extensible", () => {
  59. let o = {};
  60. Object.defineProperty(o, "foo", { value: 10, configurable: true });
  61. let p = new Proxy(o, {
  62. has() {
  63. return false;
  64. },
  65. });
  66. Object.preventExtensions(o);
  67. expect(() => {
  68. "foo" in p;
  69. }).toThrowWithMessage(
  70. TypeError,
  71. "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"
  72. );
  73. });
  74. });