Object.freeze.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. test("length is 1", () => {
  2. expect(Object.freeze).toHaveLength(1);
  3. });
  4. describe("normal behavior", () => {
  5. test("returns given argument", () => {
  6. const o = {};
  7. expect(Object.freeze(42)).toBe(42);
  8. expect(Object.freeze("foobar")).toBe("foobar");
  9. expect(Object.freeze(o)).toBe(o);
  10. });
  11. test("prevents addition of new properties", () => {
  12. const o = {};
  13. expect(o.foo).toBeUndefined();
  14. Object.freeze(o);
  15. o.foo = "bar";
  16. expect(o.foo).toBeUndefined();
  17. });
  18. test("prevents deletion of existing properties", () => {
  19. const o = { foo: "bar" };
  20. expect(o.foo).toBe("bar");
  21. Object.freeze(o);
  22. delete o.foo;
  23. expect(o.foo).toBe("bar");
  24. });
  25. test("prevents changing attributes of existing properties", () => {
  26. const o = { foo: "bar" };
  27. Object.freeze(o);
  28. // FIXME: These don't change anything and should not throw!
  29. // expect(Object.defineProperty(o, "foo", {})).toBe(o);
  30. // expect(Object.defineProperty(o, "foo", { configurable: false })).toBe(o);
  31. expect(() => {
  32. Object.defineProperty(o, "foo", { configurable: true });
  33. }).toThrowWithMessage(
  34. TypeError,
  35. "Cannot change attributes of non-configurable property 'foo'"
  36. );
  37. });
  38. test("prevents changing value of existing properties", () => {
  39. const o = { foo: "bar" };
  40. expect(o.foo).toBe("bar");
  41. Object.freeze(o);
  42. o.foo = "baz";
  43. expect(o.foo).toBe("bar");
  44. });
  45. // #6469
  46. test("works with indexed properties", () => {
  47. const a = ["foo"];
  48. expect(a[0]).toBe("foo");
  49. Object.freeze(a);
  50. a[0] = "bar";
  51. expect(a[0]).toBe("foo");
  52. });
  53. test("works with properties that are already non-configurable", () => {
  54. const o = {};
  55. Object.defineProperty(o, "foo", {
  56. value: "bar",
  57. configurable: false,
  58. writable: true,
  59. enumerable: true,
  60. });
  61. expect(o.foo).toBe("bar");
  62. Object.freeze(o);
  63. o.foo = "baz";
  64. expect(o.foo).toBe("bar");
  65. });
  66. });