Proxy.handler-set.js 2.4 KB

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