base.js
This file
Path
__tests__/base.js
2,457 lines · 61.6 KiB · JavaScript
Last changed by
chore: Merge branch 'master' of github.com:immerjs/immerMichel Weststratebefore adoption6c62eec
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, DRAFT_STATE} from "../src/internal"11import deepFreeze from "deep-freeze"12import cloneDeep from "lodash.clonedeep"13import * as lodash from "lodash"1415jest.setTimeout(1000)1617enableAllPlugins()1819const isProd = process.env.NODE_ENV === "production"2021test("immer should have no dependencies", () => {22 expect(require("../package.json").dependencies).toBeUndefined()23})2425runBaseTest("proxy (no freeze)", true, false)26runBaseTest("proxy (autofreeze)", true, true)27runBaseTest("proxy (patch listener)", true, false, true)28runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)2930runBaseTest("es5 (no freeze)", false, false)31runBaseTest("es5 (autofreeze)", false, true)32runBaseTest("es5 (patch listener)", false, false, true)33runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)3435function runBaseTest(name, useProxies, autoFreeze, useListener) {36 const listener = useListener ? function() {} : undefined37 const {produce, produceWithPatches} = createPatchedImmer({38 useProxies,39 autoFreeze40 })4142 // When `useListener` is true, append a function to the arguments of every43 // uncurried `produce` call in every test. This makes tests easier to read.44 function createPatchedImmer(options) {45 const immer = new Immer(options)4647 const {produce} = immer48 immer.produce = function(...args) {49 return typeof args[1] === "function" && args.length < 350 ? produce(...args, listener)51 : produce(...args)52 }5354 return immer55 }5657 describe(`base functionality - ${name}`, () => {58 let baseState59 let origBaseState6061 beforeEach(() => {62 origBaseState = baseState = createBaseState()63 })6465 it("returns the original state when no changes are made", () => {66 const nextState = produce(baseState, s => {67 expect(s.aProp).toBe("hi")68 expect(s.anObject.nested).toMatchObject({yummie: true})69 })70 expect(nextState).toBe(baseState)71 })7273 it("does structural sharing", () => {74 const random = Math.random()75 const nextState = produce(baseState, s => {76 s.aProp = random77 })78 expect(nextState).not.toBe(baseState)79 expect(nextState.aProp).toBe(random)80 expect(nextState.nested).toBe(baseState.nested)81 })8283 it("deep change bubbles up", () => {84 const nextState = produce(baseState, s => {85 s.anObject.nested.yummie = false86 })87 expect(nextState).not.toBe(baseState)88 expect(nextState.anObject).not.toBe(baseState.anObject)89 expect(baseState.anObject.nested.yummie).toBe(true)90 expect(nextState.anObject.nested.yummie).toBe(false)91 expect(nextState.anArray).toBe(baseState.anArray)92 })9394 it("can add props", () => {95 const nextState = produce(baseState, s => {96 s.anObject.cookie = {tasty: true}97 })98 expect(nextState).not.toBe(baseState)99 expect(nextState.anObject).not.toBe(baseState.anObject)100 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)101 expect(nextState.anObject.cookie).toEqual({tasty: true})102 })103104 it("can delete props", () => {105 const nextState = produce(baseState, s => {106 delete s.anObject.nested107 })108 expect(nextState).not.toBe(baseState)109 expect(nextState.anObject).not.toBe(baseState.anObject)110 expect(nextState.anObject.nested).toBe(undefined)111 })112113 // Found by: https://github.com/mweststrate/immer/pull/267114 it("can delete props added in the producer", () => {115 const nextState = produce(baseState, s => {116 s.anObject.test = true117 delete s.anObject.test118 })119 if (useProxies) {120 expect(nextState).not.toBe(baseState)121 expect(nextState).toEqual(baseState)122 } else {123 // The copy is avoided in ES5.124 expect(nextState).toBe(baseState)125 }126 })127128 // Found by: https://github.com/mweststrate/immer/issues/328129 it("can set a property that was just deleted", () => {130 const baseState = {a: 1}131 const nextState = produce(baseState, s => {132 delete s.a133 s.a = 2134 })135 expect(nextState.a).toBe(2)136 })137138 it("can set a property to its original value after deleting it", () => {139 const baseState = {a: {b: 1}}140 const nextState = produce(baseState, s => {141 const a = s.a142 delete s.a143 s.a = a144 })145 if (useProxies) {146 expect(nextState).not.toBe(baseState)147 expect(nextState).toEqual(baseState)148 } else {149 // The copy is avoided in ES5.150 expect(nextState).toBe(baseState)151 }152 })153154 it("can get property descriptors", () => {155 const getDescriptor = Object.getOwnPropertyDescriptor156 const baseState = deepFreeze([{a: 1}])157 produce(baseState, arr => {158 const obj = arr[0]159 const desc = {160 configurable: true,161 enumerable: true,162 ...(useProxies && {writable: true})163 }164165 // Known property166 expect(getDescriptor(obj, "a")).toMatchObject(desc)167 expect(getDescriptor(arr, 0)).toMatchObject(desc)168169 // Deleted property170 delete obj.a171 arr.pop()172 expect(getDescriptor(obj, "a")).toBeUndefined()173 expect(getDescriptor(arr, 0)).toBeUndefined()174175 // Unknown property176 expect(getDescriptor(obj, "b")).toBeUndefined()177 expect(getDescriptor(arr, 100)).toBeUndefined()178179 // Added property180 obj.b = 2181 arr[100] = 1182 expect(getDescriptor(obj, "b")).toBeDefined()183 expect(getDescriptor(arr, 100)).toBeDefined()184 })185 })186187 describe("array drafts", () => {188 it("supports Array.isArray()", () => {189 const nextState = produce(baseState, s => {190 expect(Array.isArray(s.anArray)).toBeTruthy()191 s.anArray.push(1)192 })193 expect(Array.isArray(nextState.anArray)).toBeTruthy()194 })195196 it("supports index access", () => {197 const value = baseState.anArray[0]198 const nextState = produce(baseState, s => {199 expect(s.anArray[0]).toBe(value)200 })201 expect(nextState).toBe(baseState)202 })203204 it("supports iteration", () => {205 const base = [206 {id: 1, a: 1},207 {id: 2, a: 1}208 ]209 const findById = (collection, id) => {210 for (const item of collection) {211 if (item.id === id) return item212 }213 return null214 }215 const result = produce(base, draft => {216 const obj1 = findById(draft, 1)217 const obj2 = findById(draft, 2)218 obj1.a = 2219 obj2.a = 2220 })221 expect(result[0].a).toEqual(2)222 expect(result[1].a).toEqual(2)223 })224225 it("can assign an index via bracket notation", () => {226 const nextState = produce(baseState, s => {227 s.anArray[3] = true228 })229 expect(nextState).not.toBe(baseState)230 expect(nextState.anArray).not.toBe(baseState.anArray)231 expect(nextState.anArray[3]).toEqual(true)232 })233234 it("can use splice() to both add and remove items", () => {235 const nextState = produce(baseState, s => {236 s.anArray.splice(1, 1, "a", "b")237 })238 expect(nextState.anArray).not.toBe(baseState.anArray)239 expect(nextState.anArray[1]).toBe("a")240 expect(nextState.anArray[2]).toBe("b")241 })242243 it("can truncate via the length property", () => {244 const baseLength = baseState.anArray.length245 const nextState = produce(baseState, s => {246 s.anArray.length = baseLength - 1247 })248 expect(nextState.anArray).not.toBe(baseState.anArray)249 expect(nextState.anArray.length).toBe(baseLength - 1)250 })251252 it("can extend via the length property", () => {253 const baseLength = baseState.anArray.length254 const nextState = produce(baseState, s => {255 s.anArray.length = baseLength + 1256 })257 expect(nextState.anArray).not.toBe(baseState.anArray)258 expect(nextState.anArray.length).toBe(baseLength + 1)259 })260261 // Reported here: https://github.com/mweststrate/immer/issues/116262 it("can pop then push", () => {263 const nextState = produce([1, 2, 3], s => {264 s.pop()265 s.push(100)266 })267 expect(nextState).toEqual([1, 2, 100])268 })269270 it("can be sorted", () => {271 const baseState = [3, 1, 2]272 const nextState = produce(baseState, s => {273 s.sort()274 })275 expect(nextState).not.toBe(baseState)276 expect(nextState).toEqual([1, 2, 3])277 })278279 it("supports modifying nested objects", () => {280 const baseState = [{a: 1}, {}]281 const nextState = produce(baseState, s => {282 s[0].a++283 s[1].a = 0284 })285 expect(nextState).not.toBe(baseState)286 expect(nextState[0].a).toBe(2)287 expect(nextState[1].a).toBe(0)288 })289290 it("never preserves non-numeric properties", () => {291 const baseState = []292 baseState.x = 7293 const nextState = produce(baseState, s => {294 s.push(3)295 })296 expect("x" in nextState).toBeFalsy()297 })298299 if (useProxies && !global.USES_BUILD) {300 it("throws when a non-numeric property is added", () => {301 expect(() => {302 produce([], d => {303 d.x = 3304 })305 }).toThrowErrorMatchingSnapshot()306 })307308 it("throws when a non-numeric property is deleted", () => {309 expect(() => {310 const baseState = []311 baseState.x = 7312 produce(baseState, d => {313 delete d.x314 })315 }).toThrowErrorMatchingSnapshot()316 })317 }318 })319320 describe("map drafts", () => {321 it("supports key access", () => {322 const value = baseState.aMap.get("jedi")323 const nextState = produce(baseState, s => {324 expect(s.aMap.get("jedi")).toEqual(value)325 })326 expect(nextState).toBe(baseState)327 })328329 it("supports key access for non-primitive keys", () => {330 const key = {prop: "val"}331 const base = new Map([[key, {id: 1, a: 1}]])332 const value = base.get(key)333 const nextState = produce(base, s => {334 expect(s.get(key)).toEqual(value)335 })336 expect(nextState).toBe(base)337 })338339 it("supports iteration", () => {340 const base = new Map([341 ["first", {id: 1, a: 1}],342 ["second", {id: 2, a: 1}]343 ])344 const findById = (map, id) => {345 for (const [, item] of map) {346 if (item.id === id) return item347 }348 return null349 }350 const result = produce(base, draft => {351 const obj1 = findById(draft, 1)352 const obj2 = findById(draft, 2)353 obj1.a = 2354 obj2.a = 2355 })356 expect(result).not.toBe(base)357 expect(result.get("first").a).toEqual(2)358 expect(result.get("second").a).toEqual(2)359 })360361 it("supports 'entries'", () => {362 const base = new Map([363 ["first", {id: 1, a: 1}],364 ["second", {id: 2, a: 1}]365 ])366 const findById = (map, id) => {367 for (const [, item] of map.entries()) {368 if (item.id === id) return item369 }370 return null371 }372 const result = produce(base, draft => {373 const obj1 = findById(draft, 1)374 const obj2 = findById(draft, 2)375 obj1.a = 2376 obj2.a = 2377 })378 expect(result).not.toBe(base)379 expect(result.get("first").a).toEqual(2)380 expect(result.get("second").a).toEqual(2)381 })382383 it("supports 'values'", () => {384 const base = new Map([385 ["first", {id: 1, a: 1}],386 ["second", {id: 2, a: 1}]387 ])388 const findById = (map, id) => {389 for (const item of map.values()) {390 if (item.id === id) return item391 }392 return null393 }394 const result = produce(base, draft => {395 const obj1 = findById(draft, 1)396 const obj2 = findById(draft, 2)397 obj1.a = 2398 obj2.a = 2399 })400 expect(result).not.toBe(base)401 expect(result.get("first").a).toEqual(2)402 expect(result.get("second").a).toEqual(2)403 })404405 it("supports 'keys", () => {406 const base = new Map([407 ["first", Symbol()],408 ["second", Symbol()]409 ])410 const result = produce(base, draft => {411 expect([...draft.keys()]).toEqual(["first", "second"])412 draft.set("third", Symbol())413 expect([...draft.keys()]).toEqual(["first", "second", "third"])414 })415 })416417 it("supports forEach", () => {418 const key1 = {prop: "val1"}419 const key2 = {prop: "val2"}420 const base = new Map([421 ["first", {id: 1, a: 1}],422 ["second", {id: 2, a: 1}],423 [key1, {id: 3, a: 1}],424 [key2, {id: 4, a: 1}]425 ])426 const result = produce(base, draft => {427 let sum1 = 0428 draft.forEach(({a}) => {429 sum1 += a430 })431 expect(sum1).toBe(4)432 let sum2 = 0433 draft.get("first").a = 10434 draft.get("second").a = 20435 draft.get(key1).a = 30436 draft.get(key2).a = 40437 draft.forEach(({a}) => {438 sum2 += a439 })440 expect(sum2).toBe(100)441 })442 expect(result).not.toBe(base)443 expect(base.get("first").a).toEqual(1)444 expect(base.get("second").a).toEqual(1)445 expect(base.get(key1).a).toEqual(1)446 expect(base.get(key2).a).toEqual(1)447 expect(result.get("first").a).toEqual(10)448 expect(result.get("second").a).toEqual(20)449 expect(result.get(key1).a).toEqual(30)450 expect(result.get(key2).a).toEqual(40)451 })452453 it("supports forEach mutation", () => {454 const base = new Map([455 ["first", {id: 1, a: 1}],456 ["second", {id: 2, a: 1}]457 ])458 const result = produce(base, draft => {459 draft.forEach(item => {460 item.a = 100461 })462 })463 expect(result).not.toBe(base)464 expect(result.get("first").a).toEqual(100)465 expect(result.get("second").a).toEqual(100)466 })467468 it("can assign by key", () => {469 const nextState = produce(baseState, s => {470 // Map.prototype.set should return the Map itself471 const res = s.aMap.set("force", true)472 if (!global.USES_BUILD) expect(res).toBe(s.aMap[DRAFT_STATE].draft_)473 })474 expect(nextState).not.toBe(baseState)475 expect(nextState.aMap).not.toBe(baseState.aMap)476 expect(nextState.aMap.get("force")).toEqual(true)477 })478479 it("can assign by a non-primitive key", () => {480 const key = {prop: "val"}481 const value = {id: 1, a: 1}482 const base = new Map([[key, value]])483 const nextState = produce(base, s => {484 s.set(key, true)485 })486 expect(nextState).not.toBe(base)487 expect(base.get(key)).toEqual(value)488 expect(nextState.get(key)).toEqual(true)489 })490491 it("state stays the same if the the same item is assigned by key", () => {492 const nextState = produce(baseState, s => {493 s.aMap.set("jediTotal", 42)494 })495 expect(nextState).toBe(baseState)496 expect(nextState.aMap).toBe(baseState.aMap)497 })498499 it("returns 'size'", () => {500 const nextState = produce(baseState, s => {501 s.aMap.set("newKey", true)502 expect(s.aMap.size).toBe(baseState.aMap.size + 1)503 })504 expect(nextState).not.toBe(baseState)505 expect(nextState.aMap).not.toBe(baseState.aMap)506 expect(nextState.aMap.get("newKey")).toEqual(true)507 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)508 })509510 it("can use 'delete' to remove items", () => {511 const nextState = produce(baseState, s => {512 expect(s.aMap.has("jedi")).toBe(true)513 expect(s.aMap.delete("jedi")).toBe(true)514 expect(s.aMap.has("jedi")).toBe(false)515 })516 expect(nextState.aMap).not.toBe(baseState.aMap)517 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)518 expect(baseState.aMap.has("jedi")).toBe(true)519 expect(nextState.aMap.has("jedi")).toBe(false)520 })521522 it("can use 'clear' to remove items", () => {523 const nextState = produce(baseState, s => {524 expect(s.aMap.size).not.toBe(0)525 s.aMap.clear()526 expect(s.aMap.size).toBe(0)527 })528 expect(nextState.aMap).not.toBe(baseState.aMap)529 expect(baseState.aMap.size).not.toBe(0)530 expect(nextState.aMap.size).toBe(0)531 })532533 it("support 'has'", () => {534 const nextState = produce(baseState, s => {535 expect(s.aMap.has("newKey")).toBe(false)536 s.aMap.set("newKey", true)537 expect(s.aMap.has("newKey")).toBe(true)538 })539 expect(nextState).not.toBe(baseState)540 expect(nextState.aMap).not.toBe(baseState.aMap)541 expect(baseState.aMap.has("newKey")).toBe(false)542 expect(nextState.aMap.has("newKey")).toBe(true)543 })544545 it("supports nested maps", () => {546 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])547 const result = produce(base, draft => {548 draft.get("first").get("second").prop = "test1"549 })550 expect(result).not.toBe(base)551 expect(result.get("first")).not.toBe(base.get("first"))552 expect(result.get("first").get("second")).not.toBe(553 base.get("first").get("second")554 )555 expect(base.get("first").get("second").prop).toBe("test")556 expect(result.get("first").get("second").prop).toBe("test1")557 })558559 it("treats void deletes as no-op", () => {560 const base = new Map([["x", 1]])561 const next = produce(base, d => {562 expect(d.delete("y")).toBe(false)563 })564 expect(next).toBe(base)565 })566567 it("revokes map proxies", () => {568 let m569 produce(baseState, s => {570 m = s.aMap571 })572 expect(() => m.get("x")).toThrowErrorMatchingSnapshot()573 expect(() => m.set("x", 3)).toThrowErrorMatchingSnapshot()574 })575576 it("does not draft map keys", () => {577 // anything else would be terribly confusing578 const key = {a: 1}579 const map = new Map([[key, 2]])580 const next = produce(map, d => {581 const dKey = Array.from(d.keys())[0]582 expect(isDraft(dKey)).toBe(false)583 expect(dKey).toBe(key)584 dKey.a += 1585 d.set(dKey, d.get(dKey) + 1)586 d.set(key, d.get(key) + 1)587 expect(d.get(key)).toBe(4)588 expect(key.a).toBe(2)589 })590 const entries = Array.from(next.entries())591 expect(entries).toEqual([[key, 4]])592 expect(entries[0][0]).toBe(key)593 expect(entries[0][0].a).toBe(2)594 })595596 it("does support instanceof Map", () => {597 const map = new Map()598 produce(map, d => {599 expect(d instanceof Map).toBeTruthy()600 })601 })602603 it("handles clear correctly", () => {604 const map = new Map([605 ["a", 1],606 ["c", 3]607 ])608 const next = produce(map, draft => {609 draft.delete("a")610 draft.set("b", 2)611 draft.set("c", 4)612 draft.clear()613 })614 expect(next).toEqual(new Map())615 })616 })617618 describe("set drafts", () => {619 it("supports iteration", () => {620 const base = new Set([621 {id: 1, a: 1},622 {id: 2, a: 1}623 ])624 const findById = (set, id) => {625 for (const item of set) {626 if (item.id === id) return item627 }628 return null629 }630 const result = produce(base, draft => {631 const obj1 = findById(draft, 1)632 const obj2 = findById(draft, 2)633 obj1.a = 2634 obj2.a = 2635 })636 expect(result).not.toBe(base)637 expect(base).toEqual(638 new Set([639 {id: 1, a: 1},640 {id: 2, a: 1}641 ])642 )643 expect(result).toEqual(644 new Set([645 {id: 1, a: 2},646 {id: 2, a: 2}647 ])648 )649 })650651 it("supports 'entries'", () => {652 const base = new Set([653 {id: 1, a: 1},654 {id: 2, a: 1}655 ])656 const findById = (set, id) => {657 for (const [item1, item2] of set.entries()) {658 expect(item1).toBe(item2)659 if (item1.id === id) return item1660 }661 return null662 }663 const result = produce(base, draft => {664 const obj1 = findById(draft, 1)665 const obj2 = findById(draft, 2)666 obj1.a = 2667 obj2.a = 2668 })669 expect(result).not.toBe(base)670 expect(base).toEqual(671 new Set([672 {id: 1, a: 1},673 {id: 2, a: 1}674 ])675 )676 expect(result).toEqual(677 new Set([678 {id: 1, a: 2},679 {id: 2, a: 2}680 ])681 )682 })683684 it("supports 'values'", () => {685 const base = new Set([686 {id: 1, a: 1},687 {id: 2, a: 1}688 ])689 const findById = (set, id) => {690 for (const item of set.values()) {691 if (item.id === id) return item692 }693 return null694 }695 const result = produce(base, draft => {696 const obj1 = findById(draft, 1)697 const obj2 = findById(draft, 2)698 obj1.a = 2699 obj2.a = 2700 })701 expect(result).not.toBe(base)702 expect(base).toEqual(703 new Set([704 {id: 1, a: 1},705 {id: 2, a: 1}706 ])707 )708 expect(result).toEqual(709 new Set([710 {id: 1, a: 2},711 {id: 2, a: 2}712 ])713 )714 })715716 it("supports 'keys'", () => {717 const base = new Set([718 {id: 1, a: 1},719 {id: 2, a: 1}720 ])721 const findById = (set, id) => {722 for (const item of set.keys()) {723 if (item.id === id) return item724 }725 return null726 }727 const result = produce(base, draft => {728 const obj1 = findById(draft, 1)729 const obj2 = findById(draft, 2)730 obj1.a = 2731 obj2.a = 2732 })733 expect(result).not.toBe(base)734 expect(base).toEqual(735 new Set([736 {id: 1, a: 1},737 {id: 2, a: 1}738 ])739 )740 expect(result).toEqual(741 new Set([742 {id: 1, a: 2},743 {id: 2, a: 2}744 ])745 )746 })747748 it("supports forEach with mutation after reads", () => {749 const base = new Set([750 {id: 1, a: 1},751 {id: 2, a: 2}752 ])753 const result = produce(base, draft => {754 let sum1 = 0755 draft.forEach(({a}) => {756 sum1 += a757 })758 expect(sum1).toBe(3)759 let sum2 = 0760 draft.forEach(item => {761 item.a += 10762 sum2 += item.a763 })764 expect(sum2).toBe(23)765 })766 expect(result).not.toBe(base)767 expect(base).toEqual(768 new Set([769 {id: 1, a: 1},770 {id: 2, a: 2}771 ])772 )773 expect(result).toEqual(774 new Set([775 {id: 1, a: 11},776 {id: 2, a: 12}777 ])778 )779 })780781 it("state stays the same if the same item is added", () => {782 const nextState = produce(baseState, s => {783 s.aSet.add("Luke")784 })785 expect(nextState).toBe(baseState)786 expect(nextState.aSet).toBe(baseState.aSet)787 })788789 it("can add new items", () => {790 const nextState = produce(baseState, s => {791 // Set.prototype.set should return the Set itself792 const res = s.aSet.add("force")793 if (!global.USES_BUILD) expect(res).toBe(s.aSet[DRAFT_STATE].draft_)794 })795 expect(nextState).not.toBe(baseState)796 expect(nextState.aSet).not.toBe(baseState.aSet)797 expect(baseState.aSet.has("force")).toBe(false)798 expect(nextState.aSet.has("force")).toBe(true)799 })800801 it("returns 'size'", () => {802 const nextState = produce(baseState, s => {803 s.aSet.add("newKey")804 expect(s.aSet.size).toBe(baseState.aSet.size + 1)805 })806 expect(nextState).not.toBe(baseState)807 expect(nextState.aSet).not.toBe(baseState.aSet)808 expect(nextState.aSet.has("newKey")).toBe(true)809 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)810 })811812 it("can use 'delete' to remove items", () => {813 const nextState = produce(baseState, s => {814 expect(s.aSet.has("Luke")).toBe(true)815 expect(s.aSet.delete("Luke")).toBe(true)816 expect(s.aSet.delete("Luke")).toBe(false)817 expect(s.aSet.has("Luke")).toBe(false)818 })819 expect(nextState.aSet).not.toBe(baseState.aSet)820 expect(baseState.aSet.has("Luke")).toBe(true)821 expect(nextState.aSet.has("Luke")).toBe(false)822 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)823 })824825 it("can use 'clear' to remove items", () => {826 const nextState = produce(baseState, s => {827 expect(s.aSet.size).not.toBe(0)828 s.aSet.clear()829 expect(s.aSet.size).toBe(0)830 })831 expect(nextState.aSet).not.toBe(baseState.aSet)832 expect(baseState.aSet.size).not.toBe(0)833 expect(nextState.aSet.size).toBe(0)834 })835836 it("supports 'has'", () => {837 const nextState = produce(baseState, s => {838 expect(s.aSet.has("newKey")).toBe(false)839 s.aSet.add("newKey")840 expect(s.aSet.has("newKey")).toBe(true)841 })842 expect(nextState).not.toBe(baseState)843 expect(nextState.aSet).not.toBe(baseState.aSet)844 expect(baseState.aSet.has("newKey")).toBe(false)845 expect(nextState.aSet.has("newKey")).toBe(true)846 })847848 it("supports nested sets", () => {849 const base = new Set([new Set(["Serenity"])])850 const result = produce(base, draft => {851 draft.forEach(nestedItem => nestedItem.add("Firefly"))852 })853 expect(result).not.toBe(base)854 expect(base).toEqual(new Set([new Set(["Serenity"])]))855 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))856 })857858 it("supports has / delete on elements from the original", () => {859 const obj = {}860 const set = new Set([obj])861 const next = produce(set, d => {862 expect(d.has(obj)).toBe(true)863 d.add(3)864 expect(d.has(obj)).toBe(true)865 d.delete(obj)866 expect(d.has(obj)).toBe(false)867 })868 expect(next).toEqual(new Set([3]))869 })870871 it("revokes sets", () => {872 let m873 produce(baseState, s => {874 m = s.aSet875 })876 expect(() => m.has("x")).toThrowErrorMatchingSnapshot()877 expect(() => m.add("x")).toThrowErrorMatchingSnapshot()878 })879880 it("does support instanceof Set", () => {881 const set = new Set()882 produce(set, d => {883 expect(d instanceof Set).toBeTruthy()884 })885 })886 })887888 it("supports `immerable` symbol on constructor", () => {889 class One {}890 One[immerable] = true891 const baseState = new One()892 const nextState = produce(baseState, draft => {893 expect(draft).not.toBe(baseState)894 draft.foo = true895 })896 expect(nextState).not.toBe(baseState)897 expect(nextState.foo).toBeTruthy()898 })899900 it("preserves symbol properties", () => {901 const test = Symbol("test")902 const baseState = {[test]: true}903 const nextState = produce(baseState, s => {904 expect(s[test]).toBeTruthy()905 s.foo = true906 })907 expect(nextState).toEqual({908 [test]: true,909 foo: true910 })911 })912913 if (!global.USES_BUILD)914 it("preserves non-enumerable properties", () => {915 const baseState = {}916 // Non-enumerable object property917 Object.defineProperty(baseState, "foo", {918 value: {a: 1},919 enumerable: false920 })921 // Non-enumerable primitive property922 Object.defineProperty(baseState, "bar", {923 value: 1,924 enumerable: false925 })926 const nextState = produce(baseState, s => {927 expect(s.foo).toBeTruthy()928 expect(isEnumerable(s, "foo")).toBeFalsy()929 s.bar++930 expect(isEnumerable(s, "foo")).toBeFalsy()931 s.foo.a++932 expect(isEnumerable(s, "foo")).toBeFalsy()933 })934 expect(nextState.foo).toBeTruthy()935 expect(isEnumerable(nextState, "foo")).toBeFalsy()936 })937938 it("can work with own computed props", () => {939 const baseState = {940 x: 1,941 get y() {942 return this.x943 },944 set y(v) {945 this.x = v946 }947 }948949 const nextState = produce(baseState, d => {950 expect(d.y).toBe(1)951 d.x = 2952 expect(d.x).toBe(2)953 expect(d.y).toBe(1) // this has been copied!954 d.y = 3955 expect(d.x).toBe(2)956 })957 expect(baseState.x).toBe(1)958 expect(baseState.y).toBe(1)959960 expect(nextState.x).toBe(2)961 expect(nextState.y).toBe(3)962 if (!autoFreeze) {963 nextState.y = 4 // decoupled now!964 expect(nextState.y).toBe(4)965 expect(nextState.x).toBe(2)966 expect(Object.getOwnPropertyDescriptor(nextState, "y").value).toBe(4)967 }968 })969970 it("can work with class with computed props", () => {971 class State {972 [immerable] = true973974 x = 1975976 set y(v) {977 this.x = v978 }979980 get y() {981 return this.x982 }983 }984985 const baseState = new State()986987 const nextState = produce(baseState, d => {988 expect(d.y).toBe(1)989 d.y = 2990 expect(d.x).toBe(2)991 expect(d.y).toBe(2)992 expect(Object.getOwnPropertyDescriptor(d, "y")).toBeUndefined()993 })994 expect(baseState.x).toBe(1)995 expect(baseState.y).toBe(1)996997 expect(nextState.x).toBe(2)998 expect(nextState.y).toBe(2)999 expect(Object.getOwnPropertyDescriptor(nextState, "y")).toBeUndefined()1000 })10011002 it("allows inherited computed properties", () => {1003 const proto = {}1004 Object.defineProperty(proto, "foo", {1005 get() {1006 return this.bar1007 },1008 set(val) {1009 this.bar = val1010 }1011 })1012 proto[immerable] = true1013 const baseState = Object.create(proto)1014 produce(baseState, s => {1015 expect(s.bar).toBeUndefined()1016 s.foo = {}1017 expect(s.bar).toBeDefined()1018 expect(s.foo).toBe(s.bar)1019 })1020 })10211022 it("optimization: does not visit properties of new data structures if autofreeze is disabled and no drafts are unfinalized", () => {1023 const newData = {}1024 Object.defineProperty(newData, "x", {1025 enumerable: true,1026 get() {1027 throw new Error("visited!")1028 }1029 })10301031 const run = () =>1032 produce({}, d => {1033 d.data = newData1034 })1035 if (autoFreeze) {1036 expect(run).toThrow("visited!")1037 } else {1038 expect(run).not.toThrow("visited!")1039 }1040 })10411042 it("same optimization doesn't cause draft from nested producers to be unfinished", () => {1043 const base = {1044 y: 1,1045 child: {1046 x: 11047 }1048 }1049 const wrap = produce(draft => {1050 return {1051 wrapped: draft1052 }1053 })10541055 const res = produce(base, draft => {1056 draft.y++1057 draft.child = wrap(draft.child)1058 draft.child.wrapped.x++1059 })10601061 expect(res).toEqual({1062 y: 2,1063 child: {wrapped: {x: 2}}1064 })1065 })10661067 it("supports a base state with multiple references to an object", () => {1068 const obj = {}1069 const res = produce({a: obj, b: obj}, d => {1070 // Two drafts are created for each occurrence of an object in the base state.1071 expect(d.a).not.toBe(d.b)1072 d.a.z = true1073 expect(d.b.z).toBeUndefined()1074 })1075 expect(res.b).toBe(obj)1076 expect(res.a).not.toBe(res.b)1077 expect(res.a.z).toBeTruthy()1078 })10791080 // NOTE: Except the root draft.1081 it("supports multiple references to any modified draft", () => {1082 const next = produce({a: {b: 1}}, d => {1083 d.a.b++1084 d.b = d.a1085 })1086 expect(next.a).toBe(next.b)1087 })10881089 it("can rename nested objects (no changes)", () => {1090 const nextState = produce({obj: {}}, s => {1091 s.foo = s.obj1092 delete s.obj1093 })1094 expect(nextState).toEqual({foo: {}})1095 })10961097 // Very similar to the test before, but the reused object has one1098 // property changed, one added, and one removed.1099 it("can rename nested objects (with changes)", () => {1100 const nextState = produce({obj: {a: 1, b: 1}}, s => {1101 s.obj.a = true // change1102 delete s.obj.b // delete1103 s.obj.c = true // add11041105 s.foo = s.obj1106 delete s.obj1107 })1108 expect(nextState).toEqual({foo: {a: true, c: true}})1109 })11101111 it("can nest a draft in a new object (no changes)", () => {1112 const baseState = {obj: {}}1113 const nextState = produce(baseState, s => {1114 s.foo = {bar: s.obj}1115 delete s.obj1116 })1117 expect(nextState.foo.bar).toBe(baseState.obj)1118 })11191120 it("can nest a modified draft in a new object", () => {1121 const nextState = produce({obj: {a: 1, b: 1}}, s => {1122 s.obj.a = true // change1123 delete s.obj.b // delete1124 s.obj.c = true // add11251126 s.foo = {bar: s.obj}1127 delete s.obj1128 })1129 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1130 })11311132 it("supports assigning undefined to an existing property", () => {1133 const nextState = produce(baseState, s => {1134 s.aProp = undefined1135 })1136 expect(nextState).not.toBe(baseState)1137 expect(nextState.aProp).toBe(undefined)1138 })11391140 it("supports assigning undefined to a new property", () => {1141 const baseState = {}1142 const nextState = produce(baseState, s => {1143 s.aProp = undefined1144 })1145 expect(nextState).not.toBe(baseState)1146 expect(nextState.aProp).toBe(undefined)1147 })11481149 // NOTE: ES5 drafts only protect existing properties when revoked.1150 if (!isProd)1151 it("revokes the draft once produce returns", () => {1152 const expectRevoked = (fn, shouldThrow = true) => {1153 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()1154 else expect(fn).not.toThrow()1155 }11561157 // Test object drafts:1158 let draft1159 produce({a: 1, b: 1}, s => {1160 draft = s1161 delete s.b1162 })11631164 // Access known property on object draft.1165 expectRevoked(() => {1166 draft.a1167 })11681169 // Assign known property on object draft.1170 expectRevoked(() => {1171 draft.a = true1172 })11731174 // Access unknown property on object draft.1175 expectRevoked(() => {1176 draft.z1177 }, useProxies)11781179 // Assign unknown property on object draft.1180 expectRevoked(() => {1181 draft.z = true1182 }, useProxies)11831184 // Test array drafts:1185 produce([1, 2], s => {1186 draft = s1187 s.pop()1188 })11891190 // Access known index of an array draft.1191 expectRevoked(() => {1192 draft[0]1193 })11941195 // Assign known index of an array draft.1196 expectRevoked(() => {1197 draft[0] = true1198 })11991200 // Access unknown index of an array draft.1201 expectRevoked(() => {1202 draft[1]1203 }, useProxies)12041205 // Assign unknown index of an array draft.1206 expectRevoked(() => {1207 draft[1] = true1208 }, useProxies)1209 })12101211 it("can access a child draft that was created before the draft was modified", () => {1212 produce({a: {}}, s => {1213 const before = s.a1214 s.b = 11215 expect(s.a).toBe(before)1216 })1217 })12181219 it("should reflect all changes made in the draft immediately", () => {1220 produce(baseState, draft => {1221 draft.anArray[0] = 51222 draft.anArray.unshift("test")1223 if (!global.USES_BUILD)1224 expect(enumerableOnly(draft.anArray)).toEqual([1225 "test",1226 5,1227 2,1228 {c: 3},1229 11230 ])1231 draft.stuffz = "coffee"1232 expect(draft.stuffz).toBe("coffee")1233 })1234 })12351236 if (useProxies)1237 it("throws when Object.defineProperty() is used on drafts", () => {1238 expect(() => {1239 produce({}, draft => {1240 Object.defineProperty(draft, "xx", {1241 enumerable: true,1242 writeable: true,1243 value: 21244 })1245 })1246 }).toThrowErrorMatchingSnapshot()1247 })12481249 it("should handle constructor correctly", () => {1250 const baseState = {1251 arr: new Array(),1252 obj: new Object()1253 }1254 const result = produce(baseState, draft => {1255 draft.arrConstructed = draft.arr.constructor(1)1256 draft.objConstructed = draft.obj.constructor(1)1257 })1258 expect(result.arrConstructed).toEqual(new Array().constructor(1))1259 expect(result.objConstructed).toEqual(new Object().constructor(1))1260 })12611262 it("should handle equality correctly - 1", () => {1263 const baseState = {1264 y: 3 / 0,1265 z: NaN1266 }1267 const nextState = produce(baseState, draft => {1268 draft.y = 4 / 01269 draft.z = NaN1270 })1271 expect(nextState).toBe(baseState)1272 })12731274 it("should handle equality correctly - 2", () => {1275 const baseState = {1276 x: -01277 }1278 const nextState = produce(baseState, draft => {1279 draft.x = +01280 })1281 expect(nextState).not.toBe(baseState)1282 expect(nextState).not.toEqual(baseState)1283 })12841285 // AKA: recursive produce calls1286 describe("nested producers", () => {1287 describe("when base state is not a draft", () => {1288 // This test ensures the global state used to manage proxies is1289 // never left in a corrupted state by a nested `produce` call.1290 it("never affects its parent producer implicitly", () => {1291 const base = {obj: {a: 1}}1292 const next = produce(base, draft => {1293 // Notice how `base.obj` is passed, not `draft.obj`1294 const obj2 = produce(base.obj, draft2 => {1295 draft2.a = 01296 })1297 expect(obj2.a).toBe(0)1298 expect(draft.obj.a).toBe(1) // effects should not be visible outside1299 })1300 expect(next).toBe(base)1301 })1302 })13031304 describe("when base state is a draft", () => {1305 it("always wraps the draft in a new draft", () => {1306 produce({}, parent => {1307 produce(parent, child => {1308 expect(child).not.toBe(parent)1309 expect(isDraft(child)).toBeTruthy()1310 expect(original(child)).toBe(parent)1311 })1312 })1313 })13141315 // Reported by: https://github.com/mweststrate/immer/issues/3431316 it("ensures each property is drafted", () => {1317 produce({a: {}, b: {}}, parent => {1318 parent.a // Access "a" but not "b"1319 produce(parent, child => {1320 child.c = 11321 expect(isDraft(child.a)).toBeTruthy()1322 expect(isDraft(child.b)).toBeTruthy()1323 })1324 })1325 })13261327 it("preserves any pending changes", () => {1328 produce({a: 1, b: 1, d: 1}, parent => {1329 parent.b = 21330 parent.c = 21331 delete parent.d1332 produce(parent, child => {1333 expect(child.a).toBe(1) // unchanged1334 expect(child.b).toBe(2) // changed1335 expect(child.c).toBe(2) // added1336 expect(child.d).toBeUndefined() // deleted1337 })1338 })1339 })1340 })13411342 describe("when base state contains a draft", () => {1343 it("wraps unowned draft with its own draft", () => {1344 produce({a: {}}, parent => {1345 produce({a: parent.a}, child => {1346 expect(child.a).not.toBe(parent.a)1347 expect(isDraft(child.a)).toBeTruthy()1348 expect(original(child.a)).toBe(parent.a)1349 })1350 })1351 })13521353 it("returns unowned draft if no changes were made", () => {1354 produce({a: {}}, parent => {1355 const result = produce({a: parent.a}, () => {})1356 expect(result.a).toBe(parent.a)1357 })1358 })13591360 it("clones the unowned draft when changes are made", () => {1361 produce({a: {}}, parent => {1362 const result = produce({a: parent.a}, child => {1363 child.a.b = 11364 })1365 expect(result.a).not.toBe(parent.a)1366 expect(result.a.b).toBe(1)1367 expect("b" in parent.a).toBeFalsy()1368 })1369 })13701371 // We cannot auto-freeze the result of a nested producer,1372 // because it may contain a draft from a parent producer.1373 it("never auto-freezes the result", () => {1374 produce({a: {}}, parent => {1375 const r = produce({a: parent.a}, child => {1376 child.b = 1 // Ensure a copy is returned.1377 })1378 expect(Object.isFrozen(r)).toBeFalsy()1379 })1380 })1381 })13821383 // "Upvalues" are variables from a parent scope.1384 it("does not finalize upvalue drafts", () => {1385 produce({a: {}, b: {}}, parent => {1386 expect(produce({}, () => parent)).toBe(parent)1387 parent.x // Ensure proxy not revoked.13881389 expect(produce({}, () => [parent])[0]).toBe(parent)1390 parent.x // Ensure proxy not revoked.13911392 expect(produce({}, () => parent.a)).toBe(parent.a)1393 parent.a.x // Ensure proxy not revoked.13941395 // Modified parent test1396 parent.c = 11397 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1398 parent.b.x // Ensure proxy not revoked.1399 })1400 })14011402 it("works with interweaved Immer instances", () => {1403 const options = {useProxies, autoFreeze}1404 const one = createPatchedImmer(options)1405 const two = createPatchedImmer(options)14061407 const base = {}1408 const result = one.produce(base, s1 =>1409 two.produce({s1}, s2 => {1410 expect(original(s2.s1)).toBe(s1)1411 s2.n = 11412 s2.s1 = one.produce({s2}, s3 => {1413 expect(original(s3.s2)).toBe(s2)1414 expect(original(s3.s2.s1)).toBe(s2.s1)1415 return s3.s2.s11416 })1417 })1418 )1419 expect(result.n).toBe(1)1420 expect(result.s1).toBe(base)1421 })1422 })14231424 if (useProxies)1425 it("throws when Object.setPrototypeOf() is used on a draft", () => {1426 produce({}, draft => {1427 expect(() =>1428 Object.setPrototypeOf(draft, Array)1429 ).toThrowErrorMatchingSnapshot()1430 })1431 })14321433 it("supports the 'in' operator", () => {1434 produce(baseState, draft => {1435 // Known property1436 expect("anArray" in draft).toBe(true)1437 expect(Reflect.has(draft, "anArray")).toBe(true)14381439 // Unknown property1440 expect("bla" in draft).toBe(false)1441 expect(Reflect.has(draft, "bla")).toBe(false)14421443 // Known index1444 expect(0 in draft.anArray).toBe(true)1445 expect("0" in draft.anArray).toBe(true)1446 expect(Reflect.has(draft.anArray, 0)).toBe(true)1447 expect(Reflect.has(draft.anArray, "0")).toBe(true)14481449 // Unknown index1450 expect(17 in draft.anArray).toBe(false)1451 expect("17" in draft.anArray).toBe(false)1452 expect(Reflect.has(draft.anArray, 17)).toBe(false)1453 expect(Reflect.has(draft.anArray, "17")).toBe(false)1454 })1455 })14561457 it("'this' should not be bound anymore - 1", () => {1458 const base = {x: 3}1459 const next1 = produce(base, function() {1460 expect(this).toBe(undefined)1461 })1462 })14631464 it("'this' should not be bound anymore - 2", () => {1465 const incrementor = produce(function() {1466 expect(this).toBe(undefined)1467 })1468 incrementor()1469 })14701471 it("should be possible to use dynamic bound this", () => {1472 const world = {1473 counter: {count: 1},1474 inc: produce(function(draft) {1475 expect(this).toBe(world)1476 draft.counter.count = this.counter.count + 11477 })1478 }14791480 expect(world.inc(world).counter.count).toBe(2)1481 })14821483 it("doesnt recurse into frozen structures if external data is frozen", () => {1484 const frozen = {}1485 Object.defineProperty(frozen, "x", {1486 get() {1487 throw "oops"1488 },1489 enumerable: true,1490 configurable: true1491 })1492 Object.freeze(frozen)14931494 expect(() => {1495 produce({}, d => {1496 d.x = frozen1497 })1498 }).not.toThrow()1499 })15001501 // See here: https://github.com/mweststrate/immer/issues/891502 it("supports the spread operator", () => {1503 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1504 const result = produce(base, draft => {1505 draft.foo = {x: 1, ...draft.foo, y: 1}1506 draft.bar = [1, ...draft.bar, 1]1507 })1508 expect(result).toEqual({1509 foo: {x: 0, y: 1},1510 bar: [1, 0, 0, 1]1511 })1512 })15131514 it("processes with lodash.set", () => {1515 const base = [{id: 1, a: 1}]1516 const result = produce(base, draft => {1517 lodash.set(draft, "[0].a", 2)1518 })1519 expect(base[0].a).toEqual(1)1520 expect(result[0].a).toEqual(2)1521 })15221523 it("processes with lodash.find", () => {1524 const base = [{id: 1, a: 1}]1525 const result = produce(base, draft => {1526 const obj1 = lodash.find(draft, {id: 1})1527 lodash.set(obj1, "a", 2)1528 })1529 expect(base[0].a).toEqual(1)1530 expect(result[0].a).toEqual(2)1531 })15321533 it("does not draft external data", () => {1534 const externalData = {x: 3}1535 const base = {}1536 const next = produce(base, draft => {1537 // potentially, we *could* draft external data automatically, but only if those statements are not switched...1538 draft.y = externalData1539 draft.y.x += 11540 externalData.x += 11541 })1542 expect(next).toEqual({y: {x: 5}})1543 expect(externalData.x).toBe(5)1544 expect(next.y).toBe(externalData)1545 })15461547 it("does not create new state unnecessary, #491", () => {1548 const a = {highlight: true}1549 const next1 = produce(a, draft => {1550 draft.highlight = false1551 draft.highlight = true1552 })1553 // See explanation in issue1554 expect(next1).not.toBe(a)15551556 const next2 = produce(a, draft => {1557 draft.highlight = true1558 })1559 expect(next2).toBe(a)1560 })15611562 autoFreeze &&1563 test("issue #462 - frozen", () => {1564 var origin = {1565 a: {1566 value: "no"1567 },1568 b: {1569 value: "no"1570 }1571 }1572 const next = produce(origin, draft => {1573 draft.a.value = "im"1574 })1575 expect(() => {1576 origin.b.value = "yes"1577 }).toThrowError(1578 "Cannot assign to read only property 'value' of object '#<Object>'"1579 )1580 expect(() => {1581 next.b.value = "yes"1582 }).toThrowError(1583 "Cannot assign to read only property 'value' of object '#<Object>'"1584 ) // should throw!1585 })15861587 autoFreeze &&1588 test("issue #469, state not frozen", () => {1589 const project = produce(1590 {1591 id: 1,1592 tracks: [{id: 1}]1593 },1594 () => {}1595 )15961597 expect(() => {1598 project.id = 2 // Does not throw error1599 }).toThrowError("Cannot assign to read only property 'id'")16001601 expect(() => {1602 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1603 }).toThrowError("Cannot assign to read only property 'id'")1604 })16051606 describe("recipe functions", () => {1607 it("can return a new object", () => {1608 const base = {x: 3}1609 const res = produce(base, d => {1610 return {x: d.x + 1}1611 })1612 expect(res).not.toBe(base)1613 expect(res).toEqual({x: 4})1614 })16151616 it("can return the draft", () => {1617 const base = {x: 3}1618 const res = produce(base, d => {1619 d.x = 41620 return d1621 })1622 expect(res).not.toBe(base)1623 expect(res).toEqual({x: 4})1624 })16251626 it("can return an unmodified child draft", () => {1627 const base = {a: {}}1628 const res = produce(base, d => {1629 return d.a1630 })1631 expect(res).toBe(base.a)1632 })16331634 // TODO: Avoid throwing if only the child draft was modified.1635 it("cannot return a modified child draft", () => {1636 const base = {a: {}}1637 expect(() => {1638 produce(base, d => {1639 d.a.b = 11640 return d.a1641 })1642 }).toThrowErrorMatchingSnapshot()1643 })16441645 it("can return a frozen object", () => {1646 const res = deepFreeze([{x: 3}])1647 expect(produce({}, () => res)).toBe(res)1648 })16491650 it("can return an object with two references to another object", () => {1651 const next = produce({}, d => {1652 const obj = {}1653 return {obj, arr: [obj]}1654 })1655 expect(next.obj).toBe(next.arr[0])1656 })16571658 it("can return an object with two references to an unmodified draft", () => {1659 const base = {a: {}}1660 const next = produce(base, d => {1661 return [d.a, d.a]1662 })1663 expect(next[0]).toBe(base.a)1664 expect(next[0]).toBe(next[1])1665 })16661667 it("cannot return an object that references itself", () => {1668 const res = {}1669 res.self = res1670 expect(() => {1671 produce(res, () => res.self)1672 }).toThrowErrorMatchingSnapshot()1673 })1674 })16751676 describe("async recipe function", () => {1677 it("can modify the draft", () => {1678 const base = {a: 0, b: 0}1679 return produce(base, async d => {1680 d.a = 11681 await Promise.resolve()1682 d.b = 11683 }).then(res => {1684 expect(res).not.toBe(base)1685 expect(res).toEqual({a: 1, b: 1})1686 })1687 })16881689 it("works with rejected promises", () => {1690 let draft1691 const base = {a: 0, b: 0}1692 const err = new Error("passed")1693 return produce(base, d => {1694 draft = d1695 draft.b = 11696 return Promise.reject(err)1697 }).then(1698 () => {1699 throw "failed"1700 },1701 e => {1702 expect(e).toBe(err)1703 if (!isProd) expect(() => draft.a).toThrowErrorMatchingSnapshot()1704 }1705 )1706 })17071708 it("supports recursive produce calls after await", () => {1709 const base = {obj: {k: 1}}1710 return produce(base, d => {1711 const obj = d.obj1712 delete d.obj1713 return Promise.resolve().then(() => {1714 d.a = produce({}, d => {1715 d.b = obj // Assign a draft owned by the parent scope.1716 })17171718 // Auto-freezing is prevented when an unowned draft exists.1719 expect(Object.isFrozen(d.a)).toBeFalsy()17201721 // Ensure `obj` is not revoked.1722 obj.c = 11723 })1724 }).then(res => {1725 expect(res).not.toBe(base)1726 expect(res).toEqual({1727 a: {b: {k: 1, c: 1}}1728 })1729 })1730 })1731 })17321733 it("throws when the draft is modified and another object is returned", () => {1734 const base = {x: 3}1735 expect(() => {1736 produce(base, draft => {1737 draft.x = 41738 return {x: 5}1739 })1740 }).toThrowErrorMatchingSnapshot()1741 })17421743 it("should fix #117 - 1", () => {1744 const reducer = (state, action) =>1745 produce(state, draft => {1746 switch (action.type) {1747 case "SET_STARTING_DOTS":1748 return draft.availableStartingDots.map(a => a)1749 default:1750 break1751 }1752 })1753 const base = {1754 availableStartingDots: [1755 {dots: 4, count: 1},1756 {dots: 3, count: 2},1757 {dots: 2, count: 3},1758 {dots: 1, count: 4}1759 ]1760 }1761 const next = reducer(base, {type: "SET_STARTING_DOTS"})1762 expect(next).toEqual(base.availableStartingDots)1763 expect(next).not.toBe(base.availableStartingDots)1764 })17651766 it("should fix #117 - 2", () => {1767 const reducer = (state, action) =>1768 produce(state, draft => {1769 switch (action.type) {1770 case "SET_STARTING_DOTS":1771 return {1772 dots: draft.availableStartingDots.map(a => a)1773 }1774 default:1775 break1776 }1777 })1778 const base = {1779 availableStartingDots: [1780 {dots: 4, count: 1},1781 {dots: 3, count: 2},1782 {dots: 2, count: 3},1783 {dots: 1, count: 4}1784 ]1785 }1786 const next = reducer(base, {type: "SET_STARTING_DOTS"})1787 expect(next).toEqual({dots: base.availableStartingDots})1788 })17891790 it("cannot always detect noop assignments - 0", () => {1791 const baseState = {x: {y: 3}}1792 const nextState = produce(baseState, d => {1793 const a = d.x1794 d.x = a1795 })1796 expect(nextState).toBe(baseState)1797 })17981799 it("cannot always detect noop assignments - 1", () => {1800 const baseState = {x: {y: 3}}1801 const nextState = produce(baseState, d => {1802 const a = d.x1803 d.x = 41804 d.x = a1805 })1806 // Ideally, this should actually be the same instances1807 // but this would be pretty expensive to detect,1808 // so we don't atm1809 expect(nextState).not.toBe(baseState)1810 })18111812 it("cannot always detect noop assignments - 2", () => {1813 const baseState = {x: {y: 3}}1814 const nextState = produce(baseState, d => {1815 const a = d.x1816 const stuff = a.y + 31817 d.x = 41818 d.x = a1819 })1820 // Ideally, this should actually be the same instances1821 // but this would be pretty expensive to detect,1822 // so we don't atm1823 expect(nextState).not.toBe(baseState)1824 })18251826 it("cannot always detect noop assignments - 3", () => {1827 const baseState = {x: 3}1828 const nextState = produce(baseState, d => {1829 d.x = 31830 })1831 expect(nextState).toBe(baseState)1832 })18331834 it("cannot always detect noop assignments - 4", () => {1835 const baseState = {x: 3}1836 const nextState = produce(baseState, d => {1837 d.x = 41838 d.x = 31839 })1840 // Ideally, this should actually be the same instances1841 // but this would be pretty expensive to detect,1842 // so we don't atm1843 expect(nextState).not.toBe(baseState)1844 })18451846 it("cannot always detect noop assignments - 4", () => {1847 const baseState = {}1848 const [nextState, patches] = produceWithPatches(baseState, d => {1849 d.x = 41850 delete d.x1851 })1852 expect(nextState).toEqual({})1853 expect(patches).toEqual([])1854 // This differs between ES5 and proxy, and ES5 does it better :(1855 if (useProxies) expect(nextState).not.toBe(baseState)1856 else expect(nextState).toBe(baseState)1857 })18581859 it("cannot produce undefined by returning undefined", () => {1860 const base = 31861 expect(produce(base, () => 4)).toBe(4)1862 expect(produce(base, () => null)).toBe(null)1863 expect(produce(base, () => undefined)).toBe(3)1864 expect(produce(base, () => {})).toBe(3)1865 expect(produce(base, () => nothing)).toBe(undefined)18661867 expect(produce({}, () => undefined)).toEqual({})1868 expect(produce({}, () => nothing)).toBe(undefined)1869 expect(produce(3, () => nothing)).toBe(undefined)18701871 expect(produce(() => undefined)({})).toEqual({})1872 expect(produce(() => nothing)({})).toBe(undefined)1873 expect(produce(() => nothing)(3)).toBe(undefined)1874 })18751876 describe("base state type", () => {1877 if (!global.USES_BUILD) testObjectTypes(produce)1878 testLiteralTypes(produce)1879 })18801881 afterEach(() => {1882 expect(baseState).toBe(origBaseState)1883 expect(baseState).toEqual(createBaseState())1884 })18851886 class Foo {}1887 function createBaseState() {1888 const data = {1889 anInstance: new Foo(),1890 anArray: [3, 2, {c: 3}, 1],1891 aMap: new Map([1892 ["jedi", {name: "Luke", skill: 10}],1893 ["jediTotal", 42],1894 ["force", "these aren't the droids you're looking for"]1895 ]),1896 aSet: new Set([1897 "Luke",1898 42,1899 {1900 jedi: "Yoda"1901 }1902 ]),1903 aProp: "hi",1904 anObject: {1905 nested: {1906 yummie: true1907 },1908 coffee: false1909 }1910 }1911 return autoFreeze ? deepFreeze(data) : data1912 }1913 })19141915 it(`works with spread #524 - ${name}`, () => {1916 const state = {1917 level1: {1918 level2: {1919 level3: "data"1920 }1921 }1922 }19231924 const nextState = produce(state, draft => {1925 return {...draft}1926 })1927 const nextState1 = produce(state, draft => {1928 const newLevel1 = produce(draft.level1, level1Draft => {1929 return {...level1Draft}1930 })1931 draft.level1 = newLevel11932 })19331934 const nextState2 = produce(state, draft => {1935 const newLevel1 = produce(draft.level1, level1Draft => {1936 return {...level1Draft}1937 })1938 return {1939 level1: newLevel11940 }1941 })19421943 const nextState3 = produce(state, draft => {1944 const newLevel1 = produce(draft.level1, level1Draft => {1945 return Object.assign({}, level1Draft)1946 })1947 return Object.assign(draft, {1948 level1: newLevel11949 })1950 })19511952 const expected = {level1: {level2: {level3: "data"}}}1953 expect(nextState1).toEqual(expected)1954 expect(nextState2).toEqual(expected)1955 expect(nextState3).toEqual(expected)1956 })19571958 it(`Something with nested producers #522 ${name}`, () => {1959 function initialStateFactory() {1960 return {1961 substate: {1962 array: [1963 {id: "id1", value: 0},1964 {id: "id2", value: 0}1965 ]1966 },1967 array: [1968 {id: "id1", value: 0},1969 {id: "id2", value: 0}1970 ]1971 }1972 }19731974 const globalProducer = produce(draft => {1975 draft.substate = subProducer(draft.substate)1976 draft.array = arrayProducer(draft.array)1977 }, initialStateFactory())19781979 const subProducer = produce(draftSubState => {1980 draftSubState.array = arrayProducer(draftSubState.array)1981 })19821983 const arrayProducer = produce(draftArray => {1984 draftArray[0].value += 51985 })19861987 {1988 const state = globalProducer(undefined)1989 expect(state.array[0].value).toBe(5)1990 expect(state.array.length).toBe(2)1991 expect(state.array[1]).toMatchObject({1992 id: "id2",1993 value: 01994 })1995 }19961997 {1998 const state = globalProducer(undefined)1999 expect(state.substate.array[0].value).toBe(5)2000 expect(state.substate.array.length).toBe(2)The first 2,000 of 2,457 lines.