object-spread.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. const testObjSpread = obj => {
  2. expect(obj).toEqual({
  3. foo: 0,
  4. bar: 1,
  5. baz: 2,
  6. qux: 3,
  7. });
  8. };
  9. const testObjStrSpread = obj => {
  10. expect(obj).toEqual(["a", "b", "c", "d"]);
  11. };
  12. test("spread object literal inside object literal", () => {
  13. const obj = {
  14. foo: 0,
  15. ...{ bar: 1, baz: 2 },
  16. qux: 3,
  17. };
  18. testObjSpread(obj);
  19. });
  20. test("spread object with assigned property inside object literal", () => {
  21. const obj = { foo: 0, bar: 1, baz: 2 };
  22. obj.qux = 3;
  23. testObjSpread({ ...obj });
  24. });
  25. test("spread object inside object literal", () => {
  26. let a = { bar: 1, baz: 2 };
  27. const obj = { foo: 0, ...a, qux: 3 };
  28. testObjSpread(obj);
  29. });
  30. test("complex nested object spreading", () => {
  31. const obj = {
  32. ...{},
  33. ...{
  34. ...{ foo: 0, bar: 1, baz: 2 },
  35. },
  36. qux: 3,
  37. };
  38. testObjSpread(obj);
  39. });
  40. test("spread string in object literal", () => {
  41. const obj = { ..."abcd" };
  42. testObjStrSpread(obj);
  43. });
  44. test("spread array in object literal", () => {
  45. const obj = { ...["a", "b", "c", "d"] };
  46. testObjStrSpread(obj);
  47. });
  48. test("spread string object in object literal", () => {
  49. const obj = { ...String("abcd") };
  50. testObjStrSpread(obj);
  51. });
  52. test("spread object with non-enumerable property", () => {
  53. const a = { foo: 0 };
  54. Object.defineProperty(a, "bar", {
  55. value: 1,
  56. enumerable: false,
  57. });
  58. const obj = { ...a };
  59. expect(obj.foo).toBe(0);
  60. expect(obj).not.toHaveProperty("bar");
  61. });
  62. test("spread object with symbol keys", () => {
  63. const s = Symbol("baz");
  64. const a = {
  65. foo: "bar",
  66. [s]: "qux",
  67. };
  68. const obj = { ...a };
  69. expect(obj.foo).toBe("bar");
  70. expect(obj[s]).toBe("qux");
  71. });
  72. test("spreading non-spreadable values", () => {
  73. let empty = {
  74. ...undefined,
  75. ...null,
  76. ...1,
  77. ...true,
  78. ...function () {},
  79. ...Date,
  80. };
  81. expect(Object.getOwnPropertyNames(empty)).toHaveLength(0);
  82. });
  83. test("respects custom Symbol.iterator method", () => {
  84. let o = {
  85. [Symbol.iterator]() {
  86. return {
  87. i: 0,
  88. next() {
  89. if (this.i++ == 3) {
  90. return { done: true };
  91. }
  92. return { value: this.i, done: false };
  93. },
  94. };
  95. },
  96. };
  97. let a = [...o];
  98. expect(a).toEqual([1, 2, 3]);
  99. });