base.js
This file
Path
__tests__/base.js
2,099 lines · 54.1 KiB · JavaScript
Last changed by
Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
History of this fileTake it
1"use strict"2import {3 Immer,4 nothing,5 original,6 isDraft,7 immerable,8 enableAllPlugins9} from "../src/immer"10import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/internal"11import deepFreeze from "deep-freeze"12import cloneDeep from "lodash.clonedeep"13import * as lodash from "lodash"1415jest.setTimeout(1000)1617enableAllPlugins()1819test("immer should have no dependencies", () => {20 expect(require("../package.json").dependencies).toBeUndefined()21})2223runBaseTest("proxy (no freeze)", true, false)24runBaseTest("proxy (autofreeze)", true, true)25runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)26runBaseTest("es5 (no freeze)", false, false)27runBaseTest("es5 (autofreeze)", false, true)28runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)2930function runBaseTest(name, useProxies, autoFreeze, useListener) {31 const listener = useListener ? function() {} : undefined32 const {produce, produceWithPatches} = createPatchedImmer({33 useProxies,34 autoFreeze35 })3637 // When `useListener` is true, append a function to the arguments of every38 // uncurried `produce` call in every test. This makes tests easier to read.39 function createPatchedImmer(options) {40 const immer = new Immer(options)4142 const {produce} = immer43 immer.produce = function(...args) {44 return typeof args[1] === "function" && args.length < 345 ? produce(...args, listener)46 : produce(...args)47 }4849 return immer50 }5152 describe(`base functionality - ${name}`, () => {53 let baseState54 let origBaseState5556 beforeEach(() => {57 origBaseState = baseState = createBaseState()58 })5960 it("returns the original state when no changes are made", () => {61 const nextState = produce(baseState, s => {62 expect(s.aProp).toBe("hi")63 expect(s.anObject.nested).toMatchObject({yummie: true})64 })65 expect(nextState).toBe(baseState)66 })6768 it("does structural sharing", () => {69 const random = Math.random()70 const nextState = produce(baseState, s => {71 s.aProp = random72 })73 expect(nextState).not.toBe(baseState)74 expect(nextState.aProp).toBe(random)75 expect(nextState.nested).toBe(baseState.nested)76 })7778 it("deep change bubbles up", () => {79 const nextState = produce(baseState, s => {80 s.anObject.nested.yummie = false81 })82 expect(nextState).not.toBe(baseState)83 expect(nextState.anObject).not.toBe(baseState.anObject)84 expect(baseState.anObject.nested.yummie).toBe(true)85 expect(nextState.anObject.nested.yummie).toBe(false)86 expect(nextState.anArray).toBe(baseState.anArray)87 })8889 it("can add props", () => {90 const nextState = produce(baseState, s => {91 s.anObject.cookie = {tasty: true}92 })93 expect(nextState).not.toBe(baseState)94 expect(nextState.anObject).not.toBe(baseState.anObject)95 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)96 expect(nextState.anObject.cookie).toEqual({tasty: true})97 })9899 it("can delete props", () => {100 const nextState = produce(baseState, s => {101 delete s.anObject.nested102 })103 expect(nextState).not.toBe(baseState)104 expect(nextState.anObject).not.toBe(baseState.anObject)105 expect(nextState.anObject.nested).toBe(undefined)106 })107108 // Found by: https://github.com/mweststrate/immer/pull/267109 it("can delete props added in the producer", () => {110 const nextState = produce(baseState, s => {111 s.anObject.test = true112 delete s.anObject.test113 })114 if (useProxies) {115 expect(nextState).not.toBe(baseState)116 expect(nextState).toEqual(baseState)117 } else {118 // The copy is avoided in ES5.119 expect(nextState).toBe(baseState)120 }121 })122123 // Found by: https://github.com/mweststrate/immer/issues/328124 it("can set a property that was just deleted", () => {125 const baseState = {a: 1}126 const nextState = produce(baseState, s => {127 delete s.a128 s.a = 2129 })130 expect(nextState.a).toBe(2)131 })132133 it("can set a property to its original value after deleting it", () => {134 const baseState = {a: {b: 1}}135 const nextState = produce(baseState, s => {136 const a = s.a137 delete s.a138 s.a = a139 })140 if (useProxies) {141 expect(nextState).not.toBe(baseState)142 expect(nextState).toEqual(baseState)143 } else {144 // The copy is avoided in ES5.145 expect(nextState).toBe(baseState)146 }147 })148149 it("can get property descriptors", () => {150 const getDescriptor = Object.getOwnPropertyDescriptor151 const baseState = deepFreeze([{a: 1}])152 produce(baseState, arr => {153 const obj = arr[0]154 const desc = {155 configurable: true,156 enumerable: true,157 ...(useProxies && {writable: true})158 }159160 // Known property161 expect(getDescriptor(obj, "a")).toMatchObject(desc)162 expect(getDescriptor(arr, 0)).toMatchObject(desc)163164 // Deleted property165 delete obj.a166 arr.pop()167 expect(getDescriptor(obj, "a")).toBeUndefined()168 expect(getDescriptor(arr, 0)).toBeUndefined()169170 // Unknown property171 expect(getDescriptor(obj, "b")).toBeUndefined()172 expect(getDescriptor(arr, 100)).toBeUndefined()173174 // Added property175 obj.b = 2176 arr[100] = 1177 expect(getDescriptor(obj, "b")).toBeDefined()178 expect(getDescriptor(arr, 100)).toBeDefined()179 })180 })181182 describe("array drafts", () => {183 it("supports Array.isArray()", () => {184 const nextState = produce(baseState, s => {185 expect(Array.isArray(s.anArray)).toBeTruthy()186 s.anArray.push(1)187 })188 expect(Array.isArray(nextState.anArray)).toBeTruthy()189 })190191 it("supports index access", () => {192 const value = baseState.anArray[0]193 const nextState = produce(baseState, s => {194 expect(s.anArray[0]).toBe(value)195 })196 expect(nextState).toBe(baseState)197 })198199 it("supports iteration", () => {200 const base = [201 {id: 1, a: 1},202 {id: 2, a: 1}203 ]204 const findById = (collection, id) => {205 for (const item of collection) {206 if (item.id === id) return item207 }208 return null209 }210 const result = produce(base, draft => {211 const obj1 = findById(draft, 1)212 const obj2 = findById(draft, 2)213 obj1.a = 2214 obj2.a = 2215 })216 expect(result[0].a).toEqual(2)217 expect(result[1].a).toEqual(2)218 })219220 it("can assign an index via bracket notation", () => {221 const nextState = produce(baseState, s => {222 s.anArray[3] = true223 })224 expect(nextState).not.toBe(baseState)225 expect(nextState.anArray).not.toBe(baseState.anArray)226 expect(nextState.anArray[3]).toEqual(true)227 })228229 it("can use splice() to both add and remove items", () => {230 const nextState = produce(baseState, s => {231 s.anArray.splice(1, 1, "a", "b")232 })233 expect(nextState.anArray).not.toBe(baseState.anArray)234 expect(nextState.anArray[1]).toBe("a")235 expect(nextState.anArray[2]).toBe("b")236 })237238 it("can truncate via the length property", () => {239 const baseLength = baseState.anArray.length240 const nextState = produce(baseState, s => {241 s.anArray.length = baseLength - 1242 })243 expect(nextState.anArray).not.toBe(baseState.anArray)244 expect(nextState.anArray.length).toBe(baseLength - 1)245 })246247 it("can extend via the length property", () => {248 const baseLength = baseState.anArray.length249 const nextState = produce(baseState, s => {250 s.anArray.length = baseLength + 1251 })252 expect(nextState.anArray).not.toBe(baseState.anArray)253 expect(nextState.anArray.length).toBe(baseLength + 1)254 })255256 // Reported here: https://github.com/mweststrate/immer/issues/116257 it("can pop then push", () => {258 const nextState = produce([1, 2, 3], s => {259 s.pop()260 s.push(100)261 })262 expect(nextState).toEqual([1, 2, 100])263 })264265 it("can be sorted", () => {266 const baseState = [3, 1, 2]267 const nextState = produce(baseState, s => {268 s.sort()269 })270 expect(nextState).not.toBe(baseState)271 expect(nextState).toEqual([1, 2, 3])272 })273274 it("supports modifying nested objects", () => {275 const baseState = [{a: 1}, {}]276 const nextState = produce(baseState, s => {277 s[0].a++278 s[1].a = 0279 })280 expect(nextState).not.toBe(baseState)281 expect(nextState[0].a).toBe(2)282 expect(nextState[1].a).toBe(0)283 })284285 it("never preserves non-numeric properties", () => {286 const baseState = []287 baseState.x = 7288 const nextState = produce(baseState, s => {289 s.push(3)290 })291 expect("x" in nextState).toBeFalsy()292 })293294 if (useProxies) {295 it("throws when a non-numeric property is added", () => {296 expect(() => {297 produce([], d => {298 d.x = 3299 })300 }).toThrowErrorMatchingSnapshot()301 })302303 it("throws when a non-numeric property is deleted", () => {304 expect(() => {305 const baseState = []306 baseState.x = 7307 produce(baseState, d => {308 delete d.x309 })310 }).toThrowErrorMatchingSnapshot()311 })312 }313 })314315 describe("map drafts", () => {316 it("supports key access", () => {317 const value = baseState.aMap.get("jedi")318 const nextState = produce(baseState, s => {319 expect(s.aMap.get("jedi")).toEqual(value)320 })321 expect(nextState).toBe(baseState)322 })323324 it("supports key access for non-primitive keys", () => {325 const key = {prop: "val"}326 const base = new Map([[key, {id: 1, a: 1}]])327 const value = base.get(key)328 const nextState = produce(base, s => {329 expect(s.get(key)).toEqual(value)330 })331 expect(nextState).toBe(base)332 })333334 it("supports iteration", () => {335 const base = new Map([336 ["first", {id: 1, a: 1}],337 ["second", {id: 2, a: 1}]338 ])339 const findById = (map, id) => {340 for (const [, item] of map) {341 if (item.id === id) return item342 }343 return null344 }345 const result = produce(base, draft => {346 const obj1 = findById(draft, 1)347 const obj2 = findById(draft, 2)348 obj1.a = 2349 obj2.a = 2350 })351 expect(result).not.toBe(base)352 expect(result.get("first").a).toEqual(2)353 expect(result.get("second").a).toEqual(2)354 })355356 it("supports 'entries'", () => {357 const base = new Map([358 ["first", {id: 1, a: 1}],359 ["second", {id: 2, a: 1}]360 ])361 const findById = (map, id) => {362 for (const [, item] of map.entries()) {363 if (item.id === id) return item364 }365 return null366 }367 const result = produce(base, draft => {368 const obj1 = findById(draft, 1)369 const obj2 = findById(draft, 2)370 obj1.a = 2371 obj2.a = 2372 })373 expect(result).not.toBe(base)374 expect(result.get("first").a).toEqual(2)375 expect(result.get("second").a).toEqual(2)376 })377378 it("supports 'values'", () => {379 const base = new Map([380 ["first", {id: 1, a: 1}],381 ["second", {id: 2, a: 1}]382 ])383 const findById = (map, id) => {384 for (const item of map.values()) {385 if (item.id === id) return item386 }387 return null388 }389 const result = produce(base, draft => {390 const obj1 = findById(draft, 1)391 const obj2 = findById(draft, 2)392 obj1.a = 2393 obj2.a = 2394 })395 expect(result).not.toBe(base)396 expect(result.get("first").a).toEqual(2)397 expect(result.get("second").a).toEqual(2)398 })399400 it("supports 'keys", () => {401 const base = new Map([402 ["first", Symbol()],403 ["second", Symbol()]404 ])405 const result = produce(base, draft => {406 expect([...draft.keys()]).toEqual(["first", "second"])407 draft.set("third", Symbol())408 expect([...draft.keys()]).toEqual(["first", "second", "third"])409 })410 })411412 it("supports forEach", () => {413 const key1 = {prop: "val1"}414 const key2 = {prop: "val2"}415 const base = new Map([416 ["first", {id: 1, a: 1}],417 ["second", {id: 2, a: 1}],418 [key1, {id: 3, a: 1}],419 [key2, {id: 4, a: 1}]420 ])421 const result = produce(base, draft => {422 let sum1 = 0423 draft.forEach(({a}) => {424 sum1 += a425 })426 expect(sum1).toBe(4)427 let sum2 = 0428 draft.get("first").a = 10429 draft.get("second").a = 20430 draft.get(key1).a = 30431 draft.get(key2).a = 40432 draft.forEach(({a}) => {433 sum2 += a434 })435 expect(sum2).toBe(100)436 })437 expect(result).not.toBe(base)438 expect(base.get("first").a).toEqual(1)439 expect(base.get("second").a).toEqual(1)440 expect(base.get(key1).a).toEqual(1)441 expect(base.get(key2).a).toEqual(1)442 expect(result.get("first").a).toEqual(10)443 expect(result.get("second").a).toEqual(20)444 expect(result.get(key1).a).toEqual(30)445 expect(result.get(key2).a).toEqual(40)446 })447448 it("supports forEach mutation", () => {449 const base = new Map([450 ["first", {id: 1, a: 1}],451 ["second", {id: 2, a: 1}]452 ])453 const result = produce(base, draft => {454 draft.forEach(item => {455 item.a = 100456 })457 })458 expect(result).not.toBe(base)459 expect(result.get("first").a).toEqual(100)460 expect(result.get("second").a).toEqual(100)461 })462463 it("can assign by key", () => {464 const nextState = produce(baseState, s => {465 // Map.prototype.set should return the Map itself466 const res = s.aMap.set("force", true)467 if (!global.USES_BUILD) expect(res).toBe(s.aMap[DRAFT_STATE].draft_)468 })469 expect(nextState).not.toBe(baseState)470 expect(nextState.aMap).not.toBe(baseState.aMap)471 expect(nextState.aMap.get("force")).toEqual(true)472 })473474 it("can assign by a non-primitive key", () => {475 const key = {prop: "val"}476 const value = {id: 1, a: 1}477 const base = new Map([[key, value]])478 const nextState = produce(base, s => {479 s.set(key, true)480 })481 expect(nextState).not.toBe(base)482 expect(base.get(key)).toEqual(value)483 expect(nextState.get(key)).toEqual(true)484 })485486 it("state stays the same if the the same item is assigned by key", () => {487 const nextState = produce(baseState, s => {488 s.aMap.set("jediTotal", 42)489 })490 expect(nextState).toBe(baseState)491 expect(nextState.aMap).toBe(baseState.aMap)492 })493494 it("returns 'size'", () => {495 const nextState = produce(baseState, s => {496 s.aMap.set("newKey", true)497 expect(s.aMap.size).toBe(baseState.aMap.size + 1)498 })499 expect(nextState).not.toBe(baseState)500 expect(nextState.aMap).not.toBe(baseState.aMap)501 expect(nextState.aMap.get("newKey")).toEqual(true)502 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)503 })504505 it("can use 'delete' to remove items", () => {506 const nextState = produce(baseState, s => {507 expect(s.aMap.has("jedi")).toBe(true)508 expect(s.aMap.delete("jedi")).toBe(true)509 expect(s.aMap.has("jedi")).toBe(false)510 })511 expect(nextState.aMap).not.toBe(baseState.aMap)512 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)513 expect(baseState.aMap.has("jedi")).toBe(true)514 expect(nextState.aMap.has("jedi")).toBe(false)515 })516517 it("can use 'clear' to remove items", () => {518 const nextState = produce(baseState, s => {519 expect(s.aMap.size).not.toBe(0)520 s.aMap.clear()521 expect(s.aMap.size).toBe(0)522 })523 expect(nextState.aMap).not.toBe(baseState.aMap)524 expect(baseState.aMap.size).not.toBe(0)525 expect(nextState.aMap.size).toBe(0)526 })527528 it("support 'has'", () => {529 const nextState = produce(baseState, s => {530 expect(s.aMap.has("newKey")).toBe(false)531 s.aMap.set("newKey", true)532 expect(s.aMap.has("newKey")).toBe(true)533 })534 expect(nextState).not.toBe(baseState)535 expect(nextState.aMap).not.toBe(baseState.aMap)536 expect(baseState.aMap.has("newKey")).toBe(false)537 expect(nextState.aMap.has("newKey")).toBe(true)538 })539540 it("supports nested maps", () => {541 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])542 const result = produce(base, draft => {543 draft.get("first").get("second").prop = "test1"544 })545 expect(result).not.toBe(base)546 expect(result.get("first")).not.toBe(base.get("first"))547 expect(result.get("first").get("second")).not.toBe(548 base.get("first").get("second")549 )550 expect(base.get("first").get("second").prop).toBe("test")551 expect(result.get("first").get("second").prop).toBe("test1")552 })553554 it("treats void deletes as no-op", () => {555 const base = new Map([["x", 1]])556 const next = produce(base, d => {557 expect(d.delete("y")).toBe(false)558 })559 expect(next).toBe(base)560 })561562 it("revokes map proxies", () => {563 let m564 produce(baseState, s => {565 m = s.aMap566 })567 expect(() => m.get("x")).toThrow(568 "Cannot use a proxy that has been revoked"569 )570 expect(() => m.set("x", 3)).toThrow(571 "Cannot use a proxy that has been revoked"572 )573 })574575 it("does not draft map keys", () => {576 // anything else would be terribly confusing577 const key = {a: 1}578 const map = new Map([[key, 2]])579 const next = produce(map, d => {580 const dKey = Array.from(d.keys())[0]581 expect(isDraft(dKey)).toBe(false)582 expect(dKey).toBe(key)583 dKey.a += 1584 d.set(dKey, d.get(dKey) + 1)585 d.set(key, d.get(key) + 1)586 expect(d.get(key)).toBe(4)587 expect(key.a).toBe(2)588 })589 const entries = Array.from(next.entries())590 expect(entries).toEqual([[key, 4]])591 expect(entries[0][0]).toBe(key)592 expect(entries[0][0].a).toBe(2)593 })594595 it("does support instanceof Map", () => {596 const map = new Map()597 produce(map, d => {598 expect(d instanceof Map).toBeTruthy()599 })600 })601602 it("handles clear correctly", () => {603 const map = new Map([604 ["a", 1],605 ["c", 3]606 ])607 const next = produce(map, draft => {608 draft.delete("a")609 draft.set("b", 2)610 draft.set("c", 4)611 draft.clear()612 })613 expect(next).toEqual(new Map())614 })615 })616617 describe("set drafts", () => {618 it("supports iteration", () => {619 const base = new Set([620 {id: 1, a: 1},621 {id: 2, a: 1}622 ])623 const findById = (set, id) => {624 for (const item of set) {625 if (item.id === id) return item626 }627 return null628 }629 const result = produce(base, draft => {630 const obj1 = findById(draft, 1)631 const obj2 = findById(draft, 2)632 obj1.a = 2633 obj2.a = 2634 })635 expect(result).not.toBe(base)636 expect(base).toEqual(637 new Set([638 {id: 1, a: 1},639 {id: 2, a: 1}640 ])641 )642 expect(result).toEqual(643 new Set([644 {id: 1, a: 2},645 {id: 2, a: 2}646 ])647 )648 })649650 it("supports 'entries'", () => {651 const base = new Set([652 {id: 1, a: 1},653 {id: 2, a: 1}654 ])655 const findById = (set, id) => {656 for (const [item1, item2] of set.entries()) {657 expect(item1).toBe(item2)658 if (item1.id === id) return item1659 }660 return null661 }662 const result = produce(base, draft => {663 const obj1 = findById(draft, 1)664 const obj2 = findById(draft, 2)665 obj1.a = 2666 obj2.a = 2667 })668 expect(result).not.toBe(base)669 expect(base).toEqual(670 new Set([671 {id: 1, a: 1},672 {id: 2, a: 1}673 ])674 )675 expect(result).toEqual(676 new Set([677 {id: 1, a: 2},678 {id: 2, a: 2}679 ])680 )681 })682683 it("supports 'values'", () => {684 const base = new Set([685 {id: 1, a: 1},686 {id: 2, a: 1}687 ])688 const findById = (set, id) => {689 for (const item of set.values()) {690 if (item.id === id) return item691 }692 return null693 }694 const result = produce(base, draft => {695 const obj1 = findById(draft, 1)696 const obj2 = findById(draft, 2)697 obj1.a = 2698 obj2.a = 2699 })700 expect(result).not.toBe(base)701 expect(base).toEqual(702 new Set([703 {id: 1, a: 1},704 {id: 2, a: 1}705 ])706 )707 expect(result).toEqual(708 new Set([709 {id: 1, a: 2},710 {id: 2, a: 2}711 ])712 )713 })714715 it("supports 'keys'", () => {716 const base = new Set([717 {id: 1, a: 1},718 {id: 2, a: 1}719 ])720 const findById = (set, id) => {721 for (const item of set.keys()) {722 if (item.id === id) return item723 }724 return null725 }726 const result = produce(base, draft => {727 const obj1 = findById(draft, 1)728 const obj2 = findById(draft, 2)729 obj1.a = 2730 obj2.a = 2731 })732 expect(result).not.toBe(base)733 expect(base).toEqual(734 new Set([735 {id: 1, a: 1},736 {id: 2, a: 1}737 ])738 )739 expect(result).toEqual(740 new Set([741 {id: 1, a: 2},742 {id: 2, a: 2}743 ])744 )745 })746747 it("supports forEach with mutation after reads", () => {748 const base = new Set([749 {id: 1, a: 1},750 {id: 2, a: 2}751 ])752 const result = produce(base, draft => {753 let sum1 = 0754 draft.forEach(({a}) => {755 sum1 += a756 })757 expect(sum1).toBe(3)758 let sum2 = 0759 draft.forEach(item => {760 item.a += 10761 sum2 += item.a762 })763 expect(sum2).toBe(23)764 })765 expect(result).not.toBe(base)766 expect(base).toEqual(767 new Set([768 {id: 1, a: 1},769 {id: 2, a: 2}770 ])771 )772 expect(result).toEqual(773 new Set([774 {id: 1, a: 11},775 {id: 2, a: 12}776 ])777 )778 })779780 it("state stays the same if the same item is added", () => {781 const nextState = produce(baseState, s => {782 s.aSet.add("Luke")783 })784 expect(nextState).toBe(baseState)785 expect(nextState.aSet).toBe(baseState.aSet)786 })787788 it("can add new items", () => {789 const nextState = produce(baseState, s => {790 // Set.prototype.set should return the Set itself791 const res = s.aSet.add("force")792 if (!global.USES_BUILD) expect(res).toBe(s.aSet[DRAFT_STATE].draft_)793 })794 expect(nextState).not.toBe(baseState)795 expect(nextState.aSet).not.toBe(baseState.aSet)796 expect(baseState.aSet.has("force")).toBe(false)797 expect(nextState.aSet.has("force")).toBe(true)798 })799800 it("returns 'size'", () => {801 const nextState = produce(baseState, s => {802 s.aSet.add("newKey")803 expect(s.aSet.size).toBe(baseState.aSet.size + 1)804 })805 expect(nextState).not.toBe(baseState)806 expect(nextState.aSet).not.toBe(baseState.aSet)807 expect(nextState.aSet.has("newKey")).toBe(true)808 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)809 })810811 it("can use 'delete' to remove items", () => {812 const nextState = produce(baseState, s => {813 expect(s.aSet.has("Luke")).toBe(true)814 expect(s.aSet.delete("Luke")).toBe(true)815 expect(s.aSet.delete("Luke")).toBe(false)816 expect(s.aSet.has("Luke")).toBe(false)817 })818 expect(nextState.aSet).not.toBe(baseState.aSet)819 expect(baseState.aSet.has("Luke")).toBe(true)820 expect(nextState.aSet.has("Luke")).toBe(false)821 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)822 })823824 it("can use 'clear' to remove items", () => {825 const nextState = produce(baseState, s => {826 expect(s.aSet.size).not.toBe(0)827 s.aSet.clear()828 expect(s.aSet.size).toBe(0)829 })830 expect(nextState.aSet).not.toBe(baseState.aSet)831 expect(baseState.aSet.size).not.toBe(0)832 expect(nextState.aSet.size).toBe(0)833 })834835 it("supports 'has'", () => {836 const nextState = produce(baseState, s => {837 expect(s.aSet.has("newKey")).toBe(false)838 s.aSet.add("newKey")839 expect(s.aSet.has("newKey")).toBe(true)840 })841 expect(nextState).not.toBe(baseState)842 expect(nextState.aSet).not.toBe(baseState.aSet)843 expect(baseState.aSet.has("newKey")).toBe(false)844 expect(nextState.aSet.has("newKey")).toBe(true)845 })846847 it("supports nested sets", () => {848 const base = new Set([new Set(["Serenity"])])849 const result = produce(base, draft => {850 draft.forEach(nestedItem => nestedItem.add("Firefly"))851 })852 expect(result).not.toBe(base)853 expect(base).toEqual(new Set([new Set(["Serenity"])]))854 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))855 })856857 it("supports has / delete on elements from the original", () => {858 const obj = {}859 const set = new Set([obj])860 const next = produce(set, d => {861 expect(d.has(obj)).toBe(true)862 d.add(3)863 expect(d.has(obj)).toBe(true)864 d.delete(obj)865 expect(d.has(obj)).toBe(false)866 })867 expect(next).toEqual(new Set([3]))868 })869870 it("revokes sets", () => {871 let m872 produce(baseState, s => {873 m = s.aSet874 })875 expect(() => m.has("x")).toThrow(876 "Cannot use a proxy that has been revoked"877 )878 expect(() => m.add("x")).toThrow(879 "Cannot use a proxy that has been revoked"880 )881 })882883 it("does support instanceof Set", () => {884 const set = new Set()885 produce(set, d => {886 expect(d instanceof Set).toBeTruthy()887 })888 })889 })890891 it("supports `immerable` symbol on constructor", () => {892 class One {}893 One[immerable] = true894 const baseState = new One()895 const nextState = produce(baseState, draft => {896 expect(draft).not.toBe(baseState)897 draft.foo = true898 })899 expect(nextState).not.toBe(baseState)900 expect(nextState.foo).toBeTruthy()901 })902903 it("preserves symbol properties", () => {904 const test = Symbol("test")905 const baseState = {[test]: true}906 const nextState = produce(baseState, s => {907 expect(s[test]).toBeTruthy()908 s.foo = true909 })910 expect(nextState).toEqual({911 [test]: true,912 foo: true913 })914 })915916 if (!global.USES_BUILD)917 it("preserves non-enumerable properties", () => {918 const baseState = {}919 // Non-enumerable object property920 Object.defineProperty(baseState, "foo", {921 value: {a: 1},922 enumerable: false923 })924 // Non-enumerable primitive property925 Object.defineProperty(baseState, "bar", {926 value: 1,927 enumerable: false928 })929 const nextState = produce(baseState, s => {930 expect(s.foo).toBeTruthy()931 expect(isEnumerable(s, "foo")).toBeFalsy()932 s.bar++933 expect(isEnumerable(s, "foo")).toBeFalsy()934 s.foo.a++935 expect(isEnumerable(s, "foo")).toBeFalsy()936 })937 expect(nextState.foo).toBeTruthy()938 expect(isEnumerable(nextState, "foo")).toBeFalsy()939 })940941 it("throws on computed properties", () => {942 const baseState = {}943 Object.defineProperty(baseState, "foo", {944 get: () => {},945 enumerable: true946 })947 expect(() => {948 produce(baseState, s => {949 // Proxies only throw once a change is made.950 if (useProxies) {951 s.modified = true952 }953 })954 }).toThrowErrorMatchingSnapshot()955 })956957 it("allows inherited computed properties", () => {958 const proto = {}959 Object.defineProperty(proto, "foo", {960 get() {961 return this.bar962 },963 set(val) {964 this.bar = val965 }966 })967 const baseState = Object.create(proto)968 produce(baseState, s => {969 expect(s.bar).toBeUndefined()970 s.foo = {}971 expect(s.bar).toBeDefined()972 expect(s.foo).toBe(s.bar)973 })974 })975976 it("supports a base state with multiple references to an object", () => {977 const obj = {}978 const res = produce({a: obj, b: obj}, d => {979 // Two drafts are created for each occurrence of an object in the base state.980 expect(d.a).not.toBe(d.b)981 d.a.z = true982 expect(d.b.z).toBeUndefined()983 })984 expect(res.b).toBe(obj)985 expect(res.a).not.toBe(res.b)986 expect(res.a.z).toBeTruthy()987 })988989 // NOTE: Except the root draft.990 it("supports multiple references to any modified draft", () => {991 const next = produce({a: {b: 1}}, d => {992 d.a.b++993 d.b = d.a994 })995 expect(next.a).toBe(next.b)996 })997998 it("can rename nested objects (no changes)", () => {999 const nextState = produce({obj: {}}, s => {1000 s.foo = s.obj1001 delete s.obj1002 })1003 expect(nextState).toEqual({foo: {}})1004 })10051006 // Very similar to the test before, but the reused object has one1007 // property changed, one added, and one removed.1008 it("can rename nested objects (with changes)", () => {1009 const nextState = produce({obj: {a: 1, b: 1}}, s => {1010 s.obj.a = true // change1011 delete s.obj.b // delete1012 s.obj.c = true // add10131014 s.foo = s.obj1015 delete s.obj1016 })1017 expect(nextState).toEqual({foo: {a: true, c: true}})1018 })10191020 it("can nest a draft in a new object (no changes)", () => {1021 const baseState = {obj: {}}1022 const nextState = produce(baseState, s => {1023 s.foo = {bar: s.obj}1024 delete s.obj1025 })1026 expect(nextState.foo.bar).toBe(baseState.obj)1027 })10281029 it("can nest a modified draft in a new object", () => {1030 const nextState = produce({obj: {a: 1, b: 1}}, s => {1031 s.obj.a = true // change1032 delete s.obj.b // delete1033 s.obj.c = true // add10341035 s.foo = {bar: s.obj}1036 delete s.obj1037 })1038 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1039 })10401041 it("supports assigning undefined to an existing property", () => {1042 const nextState = produce(baseState, s => {1043 s.aProp = undefined1044 })1045 expect(nextState).not.toBe(baseState)1046 expect(nextState.aProp).toBe(undefined)1047 })10481049 it("supports assigning undefined to a new property", () => {1050 const baseState = {}1051 const nextState = produce(baseState, s => {1052 s.aProp = undefined1053 })1054 expect(nextState).not.toBe(baseState)1055 expect(nextState.aProp).toBe(undefined)1056 })10571058 // NOTE: ES5 drafts only protect existing properties when revoked.1059 it("revokes the draft once produce returns", () => {1060 const expectRevoked = (fn, shouldThrow = true) => {1061 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()1062 else expect(fn).not.toThrow()1063 }10641065 // Test object drafts:1066 let draft1067 produce({a: 1, b: 1}, s => {1068 draft = s1069 delete s.b1070 })10711072 // Access known property on object draft.1073 expectRevoked(() => {1074 draft.a1075 })10761077 // Assign known property on object draft.1078 expectRevoked(() => {1079 draft.a = true1080 })10811082 // Access unknown property on object draft.1083 expectRevoked(() => {1084 draft.z1085 }, useProxies)10861087 // Assign unknown property on object draft.1088 expectRevoked(() => {1089 draft.z = true1090 }, useProxies)10911092 // Test array drafts:1093 produce([1, 2], s => {1094 draft = s1095 s.pop()1096 })10971098 // Access known index of an array draft.1099 expectRevoked(() => {1100 draft[0]1101 })11021103 // Assign known index of an array draft.1104 expectRevoked(() => {1105 draft[0] = true1106 })11071108 // Access unknown index of an array draft.1109 expectRevoked(() => {1110 draft[1]1111 }, useProxies)11121113 // Assign unknown index of an array draft.1114 expectRevoked(() => {1115 draft[1] = true1116 }, useProxies)1117 })11181119 it("can access a child draft that was created before the draft was modified", () => {1120 produce({a: {}}, s => {1121 const before = s.a1122 s.b = 11123 expect(s.a).toBe(before)1124 })1125 })11261127 it("should reflect all changes made in the draft immediately", () => {1128 produce(baseState, draft => {1129 draft.anArray[0] = 51130 draft.anArray.unshift("test")1131 if (!global.USES_BUILD)1132 expect(enumerableOnly(draft.anArray)).toEqual([1133 "test",1134 5,1135 2,1136 {c: 3},1137 11138 ])1139 draft.stuffz = "coffee"1140 expect(draft.stuffz).toBe("coffee")1141 })1142 })11431144 if (useProxies)1145 it("throws when Object.defineProperty() is used on drafts", () => {1146 expect(() => {1147 produce({}, draft => {1148 Object.defineProperty(draft, "xx", {1149 enumerable: true,1150 writeable: true,1151 value: 21152 })1153 })1154 }).toThrowErrorMatchingSnapshot()1155 })11561157 it("should handle constructor correctly", () => {1158 const baseState = {1159 arr: new Array(),1160 obj: new Object()1161 }1162 const result = produce(baseState, draft => {1163 draft.arrConstructed = draft.arr.constructor(1)1164 draft.objConstructed = draft.obj.constructor(1)1165 })1166 expect(result.arrConstructed).toEqual(new Array().constructor(1))1167 expect(result.objConstructed).toEqual(new Object().constructor(1))1168 })11691170 it("should handle equality correctly - 1", () => {1171 const baseState = {1172 y: 3 / 0,1173 z: NaN1174 }1175 const nextState = produce(baseState, draft => {1176 draft.y = 4 / 01177 draft.z = NaN1178 })1179 expect(nextState).toBe(baseState)1180 })11811182 it("should handle equality correctly - 2", () => {1183 const baseState = {1184 x: -01185 }1186 const nextState = produce(baseState, draft => {1187 draft.x = +01188 })1189 expect(nextState).not.toBe(baseState)1190 expect(nextState).not.toEqual(baseState)1191 })11921193 // AKA: recursive produce calls1194 describe("nested producers", () => {1195 describe("when base state is not a draft", () => {1196 // This test ensures the global state used to manage proxies is1197 // never left in a corrupted state by a nested `produce` call.1198 it("never affects its parent producer implicitly", () => {1199 const base = {obj: {a: 1}}1200 const next = produce(base, draft => {1201 // Notice how `base.obj` is passed, not `draft.obj`1202 const obj2 = produce(base.obj, draft2 => {1203 draft2.a = 01204 })1205 expect(obj2.a).toBe(0)1206 expect(draft.obj.a).toBe(1) // effects should not be visible outside1207 })1208 expect(next).toBe(base)1209 })1210 })12111212 describe("when base state is a draft", () => {1213 it("always wraps the draft in a new draft", () => {1214 produce({}, parent => {1215 produce(parent, child => {1216 expect(child).not.toBe(parent)1217 expect(isDraft(child)).toBeTruthy()1218 expect(original(child)).toBe(parent)1219 })1220 })1221 })12221223 // Reported by: https://github.com/mweststrate/immer/issues/3431224 it("ensures each property is drafted", () => {1225 produce({a: {}, b: {}}, parent => {1226 parent.a // Access "a" but not "b"1227 produce(parent, child => {1228 child.c = 11229 expect(isDraft(child.a)).toBeTruthy()1230 expect(isDraft(child.b)).toBeTruthy()1231 })1232 })1233 })12341235 it("preserves any pending changes", () => {1236 produce({a: 1, b: 1, d: 1}, parent => {1237 parent.b = 21238 parent.c = 21239 delete parent.d1240 produce(parent, child => {1241 expect(child.a).toBe(1) // unchanged1242 expect(child.b).toBe(2) // changed1243 expect(child.c).toBe(2) // added1244 expect(child.d).toBeUndefined() // deleted1245 })1246 })1247 })1248 })12491250 describe("when base state contains a draft", () => {1251 it("wraps unowned draft with its own draft", () => {1252 produce({a: {}}, parent => {1253 produce({a: parent.a}, child => {1254 expect(child.a).not.toBe(parent.a)1255 expect(isDraft(child.a)).toBeTruthy()1256 expect(original(child.a)).toBe(parent.a)1257 })1258 })1259 })12601261 it("returns unowned draft if no changes were made", () => {1262 produce({a: {}}, parent => {1263 const result = produce({a: parent.a}, () => {})1264 expect(result.a).toBe(parent.a)1265 })1266 })12671268 it("clones the unowned draft when changes are made", () => {1269 produce({a: {}}, parent => {1270 const result = produce({a: parent.a}, child => {1271 child.a.b = 11272 })1273 expect(result.a).not.toBe(parent.a)1274 expect(result.a.b).toBe(1)1275 expect("b" in parent.a).toBeFalsy()1276 })1277 })12781279 // We cannot auto-freeze the result of a nested producer,1280 // because it may contain a draft from a parent producer.1281 it("never auto-freezes the result", () => {1282 produce({a: {}}, parent => {1283 const r = produce({a: parent.a}, child => {1284 child.b = 1 // Ensure a copy is returned.1285 })1286 expect(Object.isFrozen(r)).toBeFalsy()1287 })1288 })1289 })12901291 // "Upvalues" are variables from a parent scope.1292 it("does not finalize upvalue drafts", () => {1293 produce({a: {}, b: {}}, parent => {1294 expect(produce({}, () => parent)).toBe(parent)1295 parent.x // Ensure proxy not revoked.12961297 expect(produce({}, () => [parent])[0]).toBe(parent)1298 parent.x // Ensure proxy not revoked.12991300 expect(produce({}, () => parent.a)).toBe(parent.a)1301 parent.a.x // Ensure proxy not revoked.13021303 // Modified parent test1304 parent.c = 11305 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1306 parent.b.x // Ensure proxy not revoked.1307 })1308 })13091310 it("works with interweaved Immer instances", () => {1311 const options = {useProxies, autoFreeze}1312 const one = createPatchedImmer(options)1313 const two = createPatchedImmer(options)13141315 const base = {}1316 const result = one.produce(base, s1 =>1317 two.produce({s1}, s2 => {1318 expect(original(s2.s1)).toBe(s1)1319 s2.n = 11320 s2.s1 = one.produce({s2}, s3 => {1321 expect(original(s3.s2)).toBe(s2)1322 expect(original(s3.s2.s1)).toBe(s2.s1)1323 return s3.s2.s11324 })1325 })1326 )1327 expect(result.n).toBe(1)1328 expect(result.s1).toBe(base)1329 })1330 })13311332 if (useProxies)1333 it("throws when Object.setPrototypeOf() is used on a draft", () => {1334 produce({}, draft => {1335 expect(() =>1336 Object.setPrototypeOf(draft, Array)1337 ).toThrowErrorMatchingSnapshot()1338 })1339 })13401341 it("supports the 'in' operator", () => {1342 produce(baseState, draft => {1343 // Known property1344 expect("anArray" in draft).toBe(true)1345 expect(Reflect.has(draft, "anArray")).toBe(true)13461347 // Unknown property1348 expect("bla" in draft).toBe(false)1349 expect(Reflect.has(draft, "bla")).toBe(false)13501351 // Known index1352 expect(0 in draft.anArray).toBe(true)1353 expect("0" in draft.anArray).toBe(true)1354 expect(Reflect.has(draft.anArray, 0)).toBe(true)1355 expect(Reflect.has(draft.anArray, "0")).toBe(true)13561357 // Unknown index1358 expect(17 in draft.anArray).toBe(false)1359 expect("17" in draft.anArray).toBe(false)1360 expect(Reflect.has(draft.anArray, 17)).toBe(false)1361 expect(Reflect.has(draft.anArray, "17")).toBe(false)1362 })1363 })13641365 it("'this' should not be bound anymore - 1", () => {1366 const base = {x: 3}1367 const next1 = produce(base, function() {1368 expect(this).toBe(undefined)1369 })1370 })13711372 it("'this' should not be bound anymore - 2", () => {1373 const incrementor = produce(function() {1374 expect(this).toBe(undefined)1375 })1376 incrementor()1377 })13781379 it("should be possible to use dynamic bound this", () => {1380 const world = {1381 counter: {count: 1},1382 inc: produce(function(draft) {1383 expect(this).toBe(world)1384 draft.counter.count = this.counter.count + 11385 })1386 }13871388 expect(world.inc(world).counter.count).toBe(2)1389 })13901391 // See here: https://github.com/mweststrate/immer/issues/891392 it("supports the spread operator", () => {1393 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1394 const result = produce(base, draft => {1395 draft.foo = {x: 1, ...draft.foo, y: 1}1396 draft.bar = [1, ...draft.bar, 1]1397 })1398 expect(result).toEqual({1399 foo: {x: 0, y: 1},1400 bar: [1, 0, 0, 1]1401 })1402 })14031404 it("processes with lodash.set", () => {1405 const base = [{id: 1, a: 1}]1406 const result = produce(base, draft => {1407 lodash.set(draft, "[0].a", 2)1408 })1409 expect(base[0].a).toEqual(1)1410 expect(result[0].a).toEqual(2)1411 })14121413 it("processes with lodash.find", () => {1414 const base = [{id: 1, a: 1}]1415 const result = produce(base, draft => {1416 const obj1 = lodash.find(draft, {id: 1})1417 lodash.set(obj1, "a", 2)1418 })1419 expect(base[0].a).toEqual(1)1420 expect(result[0].a).toEqual(2)1421 })14221423 it("does not draft external data", () => {1424 const externalData = {x: 3}1425 const base = {}1426 const next = produce(base, draft => {1427 // potentially, we *could* draft external data automatically, but only if those statements are not switched...1428 draft.y = externalData1429 draft.y.x += 11430 externalData.x += 11431 })1432 expect(next).toEqual({y: {x: 5}})1433 expect(externalData.x).toBe(5)1434 expect(next.y).toBe(externalData)1435 })14361437 it("does not create new state unnecessary, #491", () => {1438 const a = {highlight: true}1439 const next1 = produce(a, draft => {1440 draft.highlight = false1441 draft.highlight = true1442 })1443 // See explanation in issue1444 expect(next1).not.toBe(a)14451446 const next2 = produce(a, draft => {1447 draft.highlight = true1448 })1449 expect(next2).toBe(a)1450 })14511452 autoFreeze &&1453 test.skip("issue #462 - frozen", () => {1454 var origin = {1455 a: {1456 value: "no"1457 },1458 b: {1459 value: "no"1460 }1461 }1462 var im = produce(origin, origin => {1463 origin.a.value = "im"1464 })1465 expect(() => (origin.b.value = "yes")).toThrow() // should throw!1466 // to prevent this...:1467 // expect(im.b.value).toBe('no');1468 })14691470 autoFreeze &&1471 test("issue #469, state not frozen", () => {1472 const project = produce(1473 {1474 id: 1,1475 tracks: [{id: 1}]1476 },1477 () => {}1478 )14791480 expect(() => {1481 project.id = 2 // Does not throw error1482 }).toThrowError("Cannot assign to read only property 'id'")14831484 expect(() => {1485 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1486 }).toThrowError("Cannot assign to read only property 'id'")1487 })14881489 describe("recipe functions", () => {1490 it("can return a new object", () => {1491 const base = {x: 3}1492 const res = produce(base, d => {1493 return {x: d.x + 1}1494 })1495 expect(res).not.toBe(base)1496 expect(res).toEqual({x: 4})1497 })14981499 it("can return the draft", () => {1500 const base = {x: 3}1501 const res = produce(base, d => {1502 d.x = 41503 return d1504 })1505 expect(res).not.toBe(base)1506 expect(res).toEqual({x: 4})1507 })15081509 it("can return an unmodified child draft", () => {1510 const base = {a: {}}1511 const res = produce(base, d => {1512 return d.a1513 })1514 expect(res).toBe(base.a)1515 })15161517 // TODO: Avoid throwing if only the child draft was modified.1518 it("cannot return a modified child draft", () => {1519 const base = {a: {}}1520 expect(() => {1521 produce(base, d => {1522 d.a.b = 11523 return d.a1524 })1525 }).toThrowErrorMatchingSnapshot()1526 })15271528 it("can return a frozen object", () => {1529 const res = deepFreeze([{x: 3}])1530 expect(produce({}, () => res)).toBe(res)1531 })15321533 it("can return an object with two references to another object", () => {1534 const next = produce({}, d => {1535 const obj = {}1536 return {obj, arr: [obj]}1537 })1538 expect(next.obj).toBe(next.arr[0])1539 })15401541 it("can return an object with two references to an unmodified draft", () => {1542 const base = {a: {}}1543 const next = produce(base, d => {1544 return [d.a, d.a]1545 })1546 expect(next[0]).toBe(base.a)1547 expect(next[0]).toBe(next[1])1548 })15491550 it("cannot return an object that references itself", () => {1551 const res = {}1552 res.self = res1553 expect(() => {1554 produce(res, () => res.self)1555 }).toThrowErrorMatchingSnapshot()1556 })1557 })15581559 describe("async recipe function", () => {1560 it("can modify the draft", () => {1561 const base = {a: 0, b: 0}1562 return produce(base, async d => {1563 d.a = 11564 await Promise.resolve()1565 d.b = 11566 }).then(res => {1567 expect(res).not.toBe(base)1568 expect(res).toEqual({a: 1, b: 1})1569 })1570 })15711572 it("works with rejected promises", () => {1573 let draft1574 const base = {a: 0, b: 0}1575 const err = new Error("passed")1576 return produce(base, d => {1577 draft = d1578 draft.b = 11579 return Promise.reject(err)1580 }).then(1581 () => {1582 throw "failed"1583 },1584 e => {1585 expect(e).toBe(err)1586 expect(() => draft.a).toThrowErrorMatchingSnapshot()1587 }1588 )1589 })15901591 it("supports recursive produce calls after await", () => {1592 const base = {obj: {k: 1}}1593 return produce(base, d => {1594 const obj = d.obj1595 delete d.obj1596 return Promise.resolve().then(() => {1597 d.a = produce({}, d => {1598 d.b = obj // Assign a draft owned by the parent scope.1599 })16001601 // Auto-freezing is prevented when an unowned draft exists.1602 expect(Object.isFrozen(d.a)).toBeFalsy()16031604 // Ensure `obj` is not revoked.1605 obj.c = 11606 })1607 }).then(res => {1608 expect(res).not.toBe(base)1609 expect(res).toEqual({1610 a: {b: {k: 1, c: 1}}1611 })1612 })1613 })1614 })16151616 it("throws when the draft is modified and another object is returned", () => {1617 const base = {x: 3}1618 expect(() => {1619 produce(base, draft => {1620 draft.x = 41621 return {x: 5}1622 })1623 }).toThrowErrorMatchingSnapshot()1624 })16251626 it("should fix #117 - 1", () => {1627 const reducer = (state, action) =>1628 produce(state, draft => {1629 switch (action.type) {1630 case "SET_STARTING_DOTS":1631 return draft.availableStartingDots.map(a => a)1632 default:1633 break1634 }1635 })1636 const base = {1637 availableStartingDots: [1638 {dots: 4, count: 1},1639 {dots: 3, count: 2},1640 {dots: 2, count: 3},1641 {dots: 1, count: 4}1642 ]1643 }1644 const next = reducer(base, {type: "SET_STARTING_DOTS"})1645 expect(next).toEqual(base.availableStartingDots)1646 expect(next).not.toBe(base.availableStartingDots)1647 })16481649 it("should fix #117 - 2", () => {1650 const reducer = (state, action) =>1651 produce(state, draft => {1652 switch (action.type) {1653 case "SET_STARTING_DOTS":1654 return {1655 dots: draft.availableStartingDots.map(a => a)1656 }1657 default:1658 break1659 }1660 })1661 const base = {1662 availableStartingDots: [1663 {dots: 4, count: 1},1664 {dots: 3, count: 2},1665 {dots: 2, count: 3},1666 {dots: 1, count: 4}1667 ]1668 }1669 const next = reducer(base, {type: "SET_STARTING_DOTS"})1670 expect(next).toEqual({dots: base.availableStartingDots})1671 })16721673 it("cannot always detect noop assignments - 0", () => {1674 const baseState = {x: {y: 3}}1675 const nextState = produce(baseState, d => {1676 const a = d.x1677 d.x = a1678 })1679 expect(nextState).toBe(baseState)1680 })16811682 it("cannot always detect noop assignments - 1", () => {1683 const baseState = {x: {y: 3}}1684 const nextState = produce(baseState, d => {1685 const a = d.x1686 d.x = 41687 d.x = a1688 })1689 // Ideally, this should actually be the same instances1690 // but this would be pretty expensive to detect,1691 // so we don't atm1692 expect(nextState).not.toBe(baseState)1693 })16941695 it("cannot always detect noop assignments - 2", () => {1696 const baseState = {x: {y: 3}}1697 const nextState = produce(baseState, d => {1698 const a = d.x1699 const stuff = a.y + 31700 d.x = 41701 d.x = a1702 })1703 // Ideally, this should actually be the same instances1704 // but this would be pretty expensive to detect,1705 // so we don't atm1706 expect(nextState).not.toBe(baseState)1707 })17081709 it("cannot always detect noop assignments - 3", () => {1710 const baseState = {x: 3}1711 const nextState = produce(baseState, d => {1712 d.x = 31713 })1714 expect(nextState).toBe(baseState)1715 })17161717 it("cannot always detect noop assignments - 4", () => {1718 const baseState = {x: 3}1719 const nextState = produce(baseState, d => {1720 d.x = 41721 d.x = 31722 })1723 // Ideally, this should actually be the same instances1724 // but this would be pretty expensive to detect,1725 // so we don't atm1726 expect(nextState).not.toBe(baseState)1727 })17281729 it("cannot produce undefined by returning undefined", () => {1730 const base = 31731 expect(produce(base, () => 4)).toBe(4)1732 expect(produce(base, () => null)).toBe(null)1733 expect(produce(base, () => undefined)).toBe(3)1734 expect(produce(base, () => {})).toBe(3)1735 expect(produce(base, () => nothing)).toBe(undefined)17361737 expect(produce({}, () => undefined)).toEqual({})1738 expect(produce({}, () => nothing)).toBe(undefined)1739 expect(produce(3, () => nothing)).toBe(undefined)17401741 expect(produce(() => undefined)({})).toEqual({})1742 expect(produce(() => nothing)({})).toBe(undefined)1743 expect(produce(() => nothing)(3)).toBe(undefined)1744 })17451746 describe("base state type", () => {1747 if (!global.USES_BUILD) testObjectTypes(produce)1748 testLiteralTypes(produce)1749 })17501751 afterEach(() => {1752 expect(baseState).toBe(origBaseState)1753 expect(baseState).toEqual(createBaseState())1754 })17551756 class Foo {}1757 function createBaseState() {1758 const data = {1759 anInstance: new Foo(),1760 anArray: [3, 2, {c: 3}, 1],1761 aMap: new Map([1762 ["jedi", {name: "Luke", skill: 10}],1763 ["jediTotal", 42],1764 ["force", "these aren't the droids you're looking for"]1765 ]),1766 aSet: new Set([1767 "Luke",1768 42,1769 {1770 jedi: "Yoda"1771 }1772 ]),1773 aProp: "hi",1774 anObject: {1775 nested: {1776 yummie: true1777 },1778 coffee: false1779 }1780 }1781 return autoFreeze ? deepFreeze(data) : data1782 }1783 })17841785 it(`works with spread #524 - ${name}`, () => {1786 const state = {1787 level1: {1788 level2: {1789 level3: "data"1790 }1791 }1792 }17931794 const nextState = produce(state, draft => {1795 return {...draft}1796 })1797 const nextState1 = produce(state, draft => {1798 const newLevel1 = produce(draft.level1, level1Draft => {1799 return {...level1Draft}1800 })1801 draft.level1 = newLevel11802 })18031804 const nextState2 = produce(state, draft => {1805 const newLevel1 = produce(draft.level1, level1Draft => {1806 return {...level1Draft}1807 })1808 return {1809 level1: newLevel11810 }1811 })18121813 const nextState3 = produce(state, draft => {1814 const newLevel1 = produce(draft.level1, level1Draft => {1815 return Object.assign({}, level1Draft)1816 })1817 return Object.assign(draft, {1818 level1: newLevel11819 })1820 })18211822 const expected = {level1: {level2: {level3: "data"}}}1823 expect(nextState1).toEqual(expected)1824 expect(nextState2).toEqual(expected)1825 expect(nextState3).toEqual(expected)1826 })18271828 it(`Something with nested producers #522 ${name}`, () => {1829 function initialStateFactory() {1830 return {1831 substate: {1832 array: [1833 {id: "id1", value: 0},1834 {id: "id2", value: 0}1835 ]1836 },1837 array: [1838 {id: "id1", value: 0},1839 {id: "id2", value: 0}1840 ]1841 }1842 }18431844 const globalProducer = produce(draft => {1845 draft.substate = subProducer(draft.substate)1846 draft.array = arrayProducer(draft.array)1847 }, initialStateFactory())18481849 const subProducer = produce(draftSubState => {1850 draftSubState.array = arrayProducer(draftSubState.array)1851 })18521853 const arrayProducer = produce(draftArray => {1854 draftArray[0].value += 51855 })18561857 {1858 const state = globalProducer(undefined)1859 expect(state.array[0].value).toBe(5)1860 expect(state.array.length).toBe(2)1861 expect(state.array[1]).toMatchObject({1862 id: "id2",1863 value: 01864 })1865 }18661867 {1868 const state = globalProducer(undefined)1869 expect(state.substate.array[0].value).toBe(5)1870 expect(state.substate.array.length).toBe(2)1871 expect(state.substate.array[1]).toMatchObject({1872 id: "id2",1873 value: 01874 })1875 expect(state.substate.array).toMatchObject(state.array)1876 }1877 })18781879 describe(`isDraft - ${name}`, () => {1880 it("returns true for object drafts", () => {1881 produce({}, state => {1882 expect(isDraft(state)).toBeTruthy()1883 })1884 })1885 it("returns true for array drafts", () => {1886 produce([], state => {1887 expect(isDraft(state)).toBeTruthy()1888 })1889 })1890 it("returns true for objects nested in object drafts", () => {1891 produce({a: {b: {}}}, state => {1892 expect(isDraft(state.a)).toBeTruthy()1893 expect(isDraft(state.a.b)).toBeTruthy()1894 })1895 })1896 it("returns false for new objects added to a draft", () => {1897 produce({}, state => {1898 state.a = {}1899 expect(isDraft(state.a)).toBeFalsy()1900 })1901 })1902 it("returns false for objects returned by the producer", () => {1903 const object = produce(null, Object.create)1904 expect(isDraft(object)).toBeFalsy()1905 })1906 it("returns false for arrays returned by the producer", () => {1907 const array = produce(null, _ => [])1908 expect(isDraft(array)).toBeFalsy()1909 })1910 it("returns false for object drafts returned by the producer", () => {1911 const object = produce({}, state => state)1912 expect(isDraft(object)).toBeFalsy()1913 })1914 it("returns false for array drafts returned by the producer", () => {1915 const array = produce([], state => state)1916 expect(isDraft(array)).toBeFalsy()1917 })1918 })19191920 describe(`complex nesting map / set / object`, () => {1921 const a = {a: 1}1922 const b = {b: 2}1923 const c = {c: 3}1924 const set1 = new Set([a, b])1925 const set2 = new Set([c])1926 const map = new Map([1927 ["set1", set1],1928 ["set2", set2]1929 ])1930 const base = {map}19311932 function first(set) {1933 return Array.from(set.values())[0]1934 }19351936 function second(set) {1937 return Array.from(set.values())[1]1938 }19391940 test(`modify deep object`, () => {1941 const [res, patches] = produceWithPatches(base, draft => {1942 const v = first(draft.map.get("set1"))1943 expect(original(v)).toBe(a)1944 expect(v).toEqual(a)1945 expect(v).not.toBe(a)1946 v.a++1947 })1948 expect(res).toMatchSnapshot()1949 expect(patches).toMatchSnapshot()1950 expect(a.a).toBe(1)1951 expect(base.map.get("set1")).toBe(set1)1952 expect(first(base.map.get("set1"))).toBe(a)1953 expect(res).not.toBe(base)1954 expect(res.map).not.toBe(base.map)1955 expect(res.map.get("set1")).not.toBe(base.map.get("set1"))1956 expect(second(base.map.get("set1"))).toBe(b)1957 expect(base.map.get("set2")).toBe(set2)1958 expect(first(res.map.get("set1"))).toEqual({a: 2})1959 })19601961 test(`modify deep object - keep value`, () => {1962 const [res, patches] = produceWithPatches(base, draft => {1963 const v = first(draft.map.get("set1"))1964 expect(original(v)).toBe(a)1965 expect(v).toEqual(a)1966 expect(v).not.toBe(a)1967 v.a = 1 // same value1968 })1969 expect(a.a).toBe(1)1970 expect(base.map.get("set1")).toBe(set1)1971 expect(first(base.map.get("set1"))).toBe(a)1972 expect(res).toBe(base)1973 expect(res.map).toBe(base.map)1974 expect(res.map.get("set1")).toBe(base.map.get("set1"))1975 expect(first(res.map.get("set1"))).toBe(a)1976 expect(second(base.map.get("set1"))).toBe(b)1977 expect(base.map.get("set2")).toBe(set2)1978 expect(patches.length).toBe(0)1979 })1980 })1981}19821983function testObjectTypes(produce) {1984 class Foo {1985 constructor(foo) {1986 this.foo = foo1987 this[immerable] = true1988 }1989 }1990 const values = {1991 "empty object": {},1992 "plain object": {a: 1, b: 2},1993 "object (no prototype)": Object.create(null),1994 "empty array": [],1995 "plain array": [1, 2],1996 "class instance (draftable)": new Foo(1)1997 }1998 for (const name in values) {1999 const value = values[name]2000 const copy = shallowCopy(value)The first 2,000 of 2,099 lines.