Proxy.handler-set.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. set(target, prop, value) {
  23. if (target[prop] === value) {
  24. target[prop] *= 2;
  25. } else {
  26. target[prop] = value;
  27. }
  28. },
  29. });
  30. p.foo = 10;
  31. expect(p.foo).toBe(10);
  32. p.foo = 10;
  33. expect(p.foo).toBe(20);
  34. p.foo = 10;
  35. expect(p.foo).toBe(10);
  36. });
  37. });
  38. describe("[[Set]] invariants", () => {
  39. test("cannot return true for a non-configurable, non-writable property", () => {
  40. let o = {};
  41. Object.defineProperty(o, "foo", { value: 10 });
  42. let p = new Proxy(o, {
  43. set() {
  44. return true;
  45. },
  46. });
  47. expect(() => {
  48. p.foo = 12;
  49. }).toThrowWithMessage(TypeError, "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");
  50. });
  51. test("cannot return true for a non-configurable accessor property with no setter", () => {
  52. let o = {};
  53. Object.defineProperty(o, "foo", { get() {} });
  54. let p = new Proxy(o, {
  55. set() {
  56. return true;
  57. },
  58. });
  59. expect(() => {
  60. p.foo = 12;
  61. }).toThrowWithMessage(TypeError, "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");
  62. });
  63. });