base.js
This file
Path
__tests__/base.js
1,996 lines · 52.0 KiB · JavaScript
Last changed by
chore: verify build during testMichel Weststratebefore adoptionef8990b
History of this fileTake it
1"use strict"2import {Immer, nothing, original, isDraft, immerable} from "../src/index"3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/internal"4import deepFreeze from "deep-freeze"5import cloneDeep from "lodash.clonedeep"6import * as lodash from "lodash"78jest.setTimeout(1000)910test("immer should have no dependencies", () => {11 expect(require("../package.json").dependencies).toBeUndefined()12})1314runBaseTest("proxy (no freeze)", true, false)15runBaseTest("proxy (autofreeze)", true, true)16runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)17runBaseTest("es5 (no freeze)", false, false)18runBaseTest("es5 (autofreeze)", false, true)19runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)2021function runBaseTest(name, useProxies, autoFreeze, useListener) {22 const listener = useListener ? function() {} : undefined23 const {produce, produceWithPatches} = createPatchedImmer({24 useProxies,25 autoFreeze26 })2728 // When `useListener` is true, append a function to the arguments of every29 // uncurried `produce` call in every test. This makes tests easier to read.30 function createPatchedImmer(options) {31 const immer = new Immer(options)3233 const {produce} = immer34 immer.produce = function(...args) {35 return typeof args[1] === "function" && args.length < 336 ? produce(...args, listener)37 : produce(...args)38 }3940 return immer41 }4243 describe(`base functionality - ${name}`, () => {44 let baseState45 let origBaseState4647 beforeEach(() => {48 origBaseState = baseState = createBaseState()49 })5051 it("returns the original state when no changes are made", () => {52 const nextState = produce(baseState, s => {53 expect(s.aProp).toBe("hi")54 expect(s.anObject.nested).toMatchObject({yummie: true})55 })56 expect(nextState).toBe(baseState)57 })5859 it("does structural sharing", () => {60 const random = Math.random()61 const nextState = produce(baseState, s => {62 s.aProp = random63 })64 expect(nextState).not.toBe(baseState)65 expect(nextState.aProp).toBe(random)66 expect(nextState.nested).toBe(baseState.nested)67 })6869 it("deep change bubbles up", () => {70 const nextState = produce(baseState, s => {71 s.anObject.nested.yummie = false72 })73 expect(nextState).not.toBe(baseState)74 expect(nextState.anObject).not.toBe(baseState.anObject)75 expect(baseState.anObject.nested.yummie).toBe(true)76 expect(nextState.anObject.nested.yummie).toBe(false)77 expect(nextState.anArray).toBe(baseState.anArray)78 })7980 it("can add props", () => {81 const nextState = produce(baseState, s => {82 s.anObject.cookie = {tasty: true}83 })84 expect(nextState).not.toBe(baseState)85 expect(nextState.anObject).not.toBe(baseState.anObject)86 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)87 expect(nextState.anObject.cookie).toEqual({tasty: true})88 })8990 it("can delete props", () => {91 const nextState = produce(baseState, s => {92 delete s.anObject.nested93 })94 expect(nextState).not.toBe(baseState)95 expect(nextState.anObject).not.toBe(baseState.anObject)96 expect(nextState.anObject.nested).toBe(undefined)97 })9899 // Found by: https://github.com/mweststrate/immer/pull/267100 it("can delete props added in the producer", () => {101 const nextState = produce(baseState, s => {102 s.anObject.test = true103 delete s.anObject.test104 })105 if (useProxies) {106 expect(nextState).not.toBe(baseState)107 expect(nextState).toEqual(baseState)108 } else {109 // The copy is avoided in ES5.110 expect(nextState).toBe(baseState)111 }112 })113114 // Found by: https://github.com/mweststrate/immer/issues/328115 it("can set a property that was just deleted", () => {116 const baseState = {a: 1}117 const nextState = produce(baseState, s => {118 delete s.a119 s.a = 2120 })121 expect(nextState.a).toBe(2)122 })123124 it("can set a property to its original value after deleting it", () => {125 const baseState = {a: {b: 1}}126 const nextState = produce(baseState, s => {127 const a = s.a128 delete s.a129 s.a = a130 })131 if (useProxies) {132 expect(nextState).not.toBe(baseState)133 expect(nextState).toEqual(baseState)134 } else {135 // The copy is avoided in ES5.136 expect(nextState).toBe(baseState)137 }138 })139140 it("can get property descriptors", () => {141 const getDescriptor = Object.getOwnPropertyDescriptor142 const baseState = deepFreeze([{a: 1}])143 produce(baseState, arr => {144 const obj = arr[0]145 const desc = {146 configurable: true,147 enumerable: true,148 ...(useProxies && {writable: true})149 }150151 // Known property152 expect(getDescriptor(obj, "a")).toMatchObject(desc)153 expect(getDescriptor(arr, 0)).toMatchObject(desc)154155 // Deleted property156 delete obj.a157 arr.pop()158 expect(getDescriptor(obj, "a")).toBeUndefined()159 expect(getDescriptor(arr, 0)).toBeUndefined()160161 // Unknown property162 expect(getDescriptor(obj, "b")).toBeUndefined()163 expect(getDescriptor(arr, 100)).toBeUndefined()164165 // Added property166 obj.b = 2167 arr[100] = 1168 expect(getDescriptor(obj, "b")).toBeDefined()169 expect(getDescriptor(arr, 100)).toBeDefined()170 })171 })172173 describe("array drafts", () => {174 it("supports Array.isArray()", () => {175 const nextState = produce(baseState, s => {176 expect(Array.isArray(s.anArray)).toBeTruthy()177 s.anArray.push(1)178 })179 expect(Array.isArray(nextState.anArray)).toBeTruthy()180 })181182 it("supports index access", () => {183 const value = baseState.anArray[0]184 const nextState = produce(baseState, s => {185 expect(s.anArray[0]).toBe(value)186 })187 expect(nextState).toBe(baseState)188 })189190 it("supports iteration", () => {191 const base = [192 {id: 1, a: 1},193 {id: 2, a: 1}194 ]195 const findById = (collection, id) => {196 for (const item of collection) {197 if (item.id === id) return item198 }199 return null200 }201 const result = produce(base, draft => {202 const obj1 = findById(draft, 1)203 const obj2 = findById(draft, 2)204 obj1.a = 2205 obj2.a = 2206 })207 expect(result[0].a).toEqual(2)208 expect(result[1].a).toEqual(2)209 })210211 it("can assign an index via bracket notation", () => {212 const nextState = produce(baseState, s => {213 s.anArray[3] = true214 })215 expect(nextState).not.toBe(baseState)216 expect(nextState.anArray).not.toBe(baseState.anArray)217 expect(nextState.anArray[3]).toEqual(true)218 })219220 it("can use splice() to both add and remove items", () => {221 const nextState = produce(baseState, s => {222 s.anArray.splice(1, 1, "a", "b")223 })224 expect(nextState.anArray).not.toBe(baseState.anArray)225 expect(nextState.anArray[1]).toBe("a")226 expect(nextState.anArray[2]).toBe("b")227 })228229 it("can truncate via the length property", () => {230 const baseLength = baseState.anArray.length231 const nextState = produce(baseState, s => {232 s.anArray.length = baseLength - 1233 })234 expect(nextState.anArray).not.toBe(baseState.anArray)235 expect(nextState.anArray.length).toBe(baseLength - 1)236 })237238 it("can extend 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 // Reported here: https://github.com/mweststrate/immer/issues/116248 it("can pop then push", () => {249 const nextState = produce([1, 2, 3], s => {250 s.pop()251 s.push(100)252 })253 expect(nextState).toEqual([1, 2, 100])254 })255256 it("can be sorted", () => {257 const baseState = [3, 1, 2]258 const nextState = produce(baseState, s => {259 s.sort()260 })261 expect(nextState).not.toBe(baseState)262 expect(nextState).toEqual([1, 2, 3])263 })264265 it("supports modifying nested objects", () => {266 const baseState = [{a: 1}, {}]267 const nextState = produce(baseState, s => {268 s[0].a++269 s[1].a = 0270 })271 expect(nextState).not.toBe(baseState)272 expect(nextState[0].a).toBe(2)273 expect(nextState[1].a).toBe(0)274 })275276 it("never preserves non-numeric properties", () => {277 const baseState = []278 baseState.x = 7279 const nextState = produce(baseState, s => {280 s.push(3)281 })282 expect("x" in nextState).toBeFalsy()283 })284285 if (useProxies) {286 it("throws when a non-numeric property is added", () => {287 expect(() => {288 produce([], d => {289 d.x = 3290 })291 }).toThrowErrorMatchingSnapshot()292 })293294 it("throws when a non-numeric property is deleted", () => {295 expect(() => {296 const baseState = []297 baseState.x = 7298 produce(baseState, d => {299 delete d.x300 })301 }).toThrowErrorMatchingSnapshot()302 })303 }304 })305306 describe("map drafts", () => {307 it("supports key access", () => {308 const value = baseState.aMap.get("jedi")309 const nextState = produce(baseState, s => {310 expect(s.aMap.get("jedi")).toEqual(value)311 })312 expect(nextState).toBe(baseState)313 })314315 it("supports key access for non-primitive keys", () => {316 const key = {prop: "val"}317 const base = new Map([[key, {id: 1, a: 1}]])318 const value = base.get(key)319 const nextState = produce(base, s => {320 expect(s.get(key)).toEqual(value)321 })322 expect(nextState).toBe(base)323 })324325 it("supports iteration", () => {326 const base = new Map([327 ["first", {id: 1, a: 1}],328 ["second", {id: 2, a: 1}]329 ])330 const findById = (map, id) => {331 for (const [, item] of map) {332 if (item.id === id) return item333 }334 return null335 }336 const result = produce(base, draft => {337 const obj1 = findById(draft, 1)338 const obj2 = findById(draft, 2)339 obj1.a = 2340 obj2.a = 2341 })342 expect(result).not.toBe(base)343 expect(result.get("first").a).toEqual(2)344 expect(result.get("second").a).toEqual(2)345 })346347 it("supports 'entries'", () => {348 const base = new Map([349 ["first", {id: 1, a: 1}],350 ["second", {id: 2, a: 1}]351 ])352 const findById = (map, id) => {353 for (const [, item] of map.entries()) {354 if (item.id === id) return item355 }356 return null357 }358 const result = produce(base, draft => {359 const obj1 = findById(draft, 1)360 const obj2 = findById(draft, 2)361 obj1.a = 2362 obj2.a = 2363 })364 expect(result).not.toBe(base)365 expect(result.get("first").a).toEqual(2)366 expect(result.get("second").a).toEqual(2)367 })368369 it("supports 'values'", () => {370 const base = new Map([371 ["first", {id: 1, a: 1}],372 ["second", {id: 2, a: 1}]373 ])374 const findById = (map, id) => {375 for (const item of map.values()) {376 if (item.id === id) return item377 }378 return null379 }380 const result = produce(base, draft => {381 const obj1 = findById(draft, 1)382 const obj2 = findById(draft, 2)383 obj1.a = 2384 obj2.a = 2385 })386 expect(result).not.toBe(base)387 expect(result.get("first").a).toEqual(2)388 expect(result.get("second").a).toEqual(2)389 })390391 it("supports 'keys", () => {392 const base = new Map([393 ["first", Symbol()],394 ["second", Symbol()]395 ])396 const result = produce(base, draft => {397 expect([...draft.keys()]).toEqual(["first", "second"])398 draft.set("third", Symbol())399 expect([...draft.keys()]).toEqual(["first", "second", "third"])400 })401 })402403 it("supports forEach", () => {404 const key1 = {prop: "val1"}405 const key2 = {prop: "val2"}406 const base = new Map([407 ["first", {id: 1, a: 1}],408 ["second", {id: 2, a: 1}],409 [key1, {id: 3, a: 1}],410 [key2, {id: 4, a: 1}]411 ])412 const result = produce(base, draft => {413 let sum1 = 0414 draft.forEach(({a}) => {415 sum1 += a416 })417 expect(sum1).toBe(4)418 let sum2 = 0419 draft.get("first").a = 10420 draft.get("second").a = 20421 draft.get(key1).a = 30422 draft.get(key2).a = 40423 draft.forEach(({a}) => {424 sum2 += a425 })426 expect(sum2).toBe(100)427 })428 expect(result).not.toBe(base)429 expect(base.get("first").a).toEqual(1)430 expect(base.get("second").a).toEqual(1)431 expect(base.get(key1).a).toEqual(1)432 expect(base.get(key2).a).toEqual(1)433 expect(result.get("first").a).toEqual(10)434 expect(result.get("second").a).toEqual(20)435 expect(result.get(key1).a).toEqual(30)436 expect(result.get(key2).a).toEqual(40)437 })438439 it("supports forEach mutation", () => {440 const base = new Map([441 ["first", {id: 1, a: 1}],442 ["second", {id: 2, a: 1}]443 ])444 const result = produce(base, draft => {445 draft.forEach(item => {446 item.a = 100447 })448 })449 expect(result).not.toBe(base)450 expect(result.get("first").a).toEqual(100)451 expect(result.get("second").a).toEqual(100)452 })453454 it("can assign by key", () => {455 const nextState = produce(baseState, s => {456 // Map.prototype.set should return the Map itself457 const res = s.aMap.set("force", true)458 if (!global.USES_BUILD) expect(res).toBe(s.aMap[DRAFT_STATE].draft)459 })460 expect(nextState).not.toBe(baseState)461 expect(nextState.aMap).not.toBe(baseState.aMap)462 expect(nextState.aMap.get("force")).toEqual(true)463 })464465 it("can assign by a non-primitive key", () => {466 const key = {prop: "val"}467 const value = {id: 1, a: 1}468 const base = new Map([[key, value]])469 const nextState = produce(base, s => {470 s.set(key, true)471 })472 expect(nextState).not.toBe(base)473 expect(base.get(key)).toEqual(value)474 expect(nextState.get(key)).toEqual(true)475 })476477 it("state stays the same if the the same item is assigned by key", () => {478 const nextState = produce(baseState, s => {479 s.aMap.set("jediTotal", 42)480 })481 expect(nextState).toBe(baseState)482 expect(nextState.aMap).toBe(baseState.aMap)483 })484485 it("returns 'size'", () => {486 const nextState = produce(baseState, s => {487 s.aMap.set("newKey", true)488 expect(s.aMap.size).toBe(baseState.aMap.size + 1)489 })490 expect(nextState).not.toBe(baseState)491 expect(nextState.aMap).not.toBe(baseState.aMap)492 expect(nextState.aMap.get("newKey")).toEqual(true)493 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)494 })495496 it("can use 'delete' to remove items", () => {497 const nextState = produce(baseState, s => {498 expect(s.aMap.has("jedi")).toBe(true)499 expect(s.aMap.delete("jedi")).toBe(true)500 expect(s.aMap.has("jedi")).toBe(false)501 })502 expect(nextState.aMap).not.toBe(baseState.aMap)503 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)504 expect(baseState.aMap.has("jedi")).toBe(true)505 expect(nextState.aMap.has("jedi")).toBe(false)506 })507508 it("can use 'clear' to remove items", () => {509 const nextState = produce(baseState, s => {510 expect(s.aMap.size).not.toBe(0)511 s.aMap.clear()512 expect(s.aMap.size).toBe(0)513 })514 expect(nextState.aMap).not.toBe(baseState.aMap)515 expect(baseState.aMap.size).not.toBe(0)516 expect(nextState.aMap.size).toBe(0)517 })518519 it("support 'has'", () => {520 const nextState = produce(baseState, s => {521 expect(s.aMap.has("newKey")).toBe(false)522 s.aMap.set("newKey", true)523 expect(s.aMap.has("newKey")).toBe(true)524 })525 expect(nextState).not.toBe(baseState)526 expect(nextState.aMap).not.toBe(baseState.aMap)527 expect(baseState.aMap.has("newKey")).toBe(false)528 expect(nextState.aMap.has("newKey")).toBe(true)529 })530531 it("supports nested maps", () => {532 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])533 const result = produce(base, draft => {534 draft.get("first").get("second").prop = "test1"535 })536 expect(result).not.toBe(base)537 expect(result.get("first")).not.toBe(base.get("first"))538 expect(result.get("first").get("second")).not.toBe(539 base.get("first").get("second")540 )541 expect(base.get("first").get("second").prop).toBe("test")542 expect(result.get("first").get("second").prop).toBe("test1")543 })544545 it("treats void deletes as no-op", () => {546 const base = new Map([["x", 1]])547 const next = produce(base, d => {548 expect(d.delete("y")).toBe(false)549 })550 expect(next).toBe(base)551 })552553 it("revokes map proxies", () => {554 let m555 produce(baseState, s => {556 m = s.aMap557 })558 expect(() => m.get("x")).toThrow(559 "Cannot use a proxy that has been revoked"560 )561 expect(() => m.set("x", 3)).toThrow(562 "Cannot use a proxy that has been revoked"563 )564 })565566 it("does not draft map keys", () => {567 // anything else would be terribly confusing568 const key = {a: 1}569 const map = new Map([[key, 2]])570 const next = produce(map, d => {571 const dKey = Array.from(d.keys())[0]572 expect(isDraft(dKey)).toBe(false)573 expect(dKey).toBe(key)574 dKey.a += 1575 d.set(dKey, d.get(dKey) + 1)576 d.set(key, d.get(key) + 1)577 expect(d.get(key)).toBe(4)578 expect(key.a).toBe(2)579 })580 const entries = Array.from(next.entries())581 expect(entries).toEqual([[key, 4]])582 expect(entries[0][0]).toBe(key)583 expect(entries[0][0].a).toBe(2)584 })585586 it("does support instanceof Map", () => {587 const map = new Map()588 produce(map, d => {589 expect(d instanceof Map).toBeTruthy()590 })591 })592593 it("handles clear correctly", () => {594 const map = new Map([595 ["a", 1],596 ["c", 3]597 ])598 const next = produce(map, draft => {599 draft.delete("a")600 draft.set("b", 2)601 draft.set("c", 4)602 draft.clear()603 })604 expect(next).toEqual(new Map())605 })606 })607608 describe("set drafts", () => {609 it("supports iteration", () => {610 const base = new Set([611 {id: 1, a: 1},612 {id: 2, a: 1}613 ])614 const findById = (set, id) => {615 for (const item of set) {616 if (item.id === id) return item617 }618 return null619 }620 const result = produce(base, draft => {621 const obj1 = findById(draft, 1)622 const obj2 = findById(draft, 2)623 obj1.a = 2624 obj2.a = 2625 })626 expect(result).not.toBe(base)627 expect(base).toEqual(628 new Set([629 {id: 1, a: 1},630 {id: 2, a: 1}631 ])632 )633 expect(result).toEqual(634 new Set([635 {id: 1, a: 2},636 {id: 2, a: 2}637 ])638 )639 })640641 it("supports 'entries'", () => {642 const base = new Set([643 {id: 1, a: 1},644 {id: 2, a: 1}645 ])646 const findById = (set, id) => {647 for (const [item1, item2] of set.entries()) {648 expect(item1).toBe(item2)649 if (item1.id === id) return item1650 }651 return null652 }653 const result = produce(base, draft => {654 const obj1 = findById(draft, 1)655 const obj2 = findById(draft, 2)656 obj1.a = 2657 obj2.a = 2658 })659 expect(result).not.toBe(base)660 expect(base).toEqual(661 new Set([662 {id: 1, a: 1},663 {id: 2, a: 1}664 ])665 )666 expect(result).toEqual(667 new Set([668 {id: 1, a: 2},669 {id: 2, a: 2}670 ])671 )672 })673674 it("supports 'values'", () => {675 const base = new Set([676 {id: 1, a: 1},677 {id: 2, a: 1}678 ])679 const findById = (set, id) => {680 for (const item of set.values()) {681 if (item.id === id) return item682 }683 return null684 }685 const result = produce(base, draft => {686 const obj1 = findById(draft, 1)687 const obj2 = findById(draft, 2)688 obj1.a = 2689 obj2.a = 2690 })691 expect(result).not.toBe(base)692 expect(base).toEqual(693 new Set([694 {id: 1, a: 1},695 {id: 2, a: 1}696 ])697 )698 expect(result).toEqual(699 new Set([700 {id: 1, a: 2},701 {id: 2, a: 2}702 ])703 )704 })705706 it("supports 'keys'", () => {707 const base = new Set([708 {id: 1, a: 1},709 {id: 2, a: 1}710 ])711 const findById = (set, id) => {712 for (const item of set.keys()) {713 if (item.id === id) return item714 }715 return null716 }717 const result = produce(base, draft => {718 const obj1 = findById(draft, 1)719 const obj2 = findById(draft, 2)720 obj1.a = 2721 obj2.a = 2722 })723 expect(result).not.toBe(base)724 expect(base).toEqual(725 new Set([726 {id: 1, a: 1},727 {id: 2, a: 1}728 ])729 )730 expect(result).toEqual(731 new Set([732 {id: 1, a: 2},733 {id: 2, a: 2}734 ])735 )736 })737738 it("supports forEach with mutation after reads", () => {739 const base = new Set([740 {id: 1, a: 1},741 {id: 2, a: 2}742 ])743 const result = produce(base, draft => {744 let sum1 = 0745 draft.forEach(({a}) => {746 sum1 += a747 })748 expect(sum1).toBe(3)749 let sum2 = 0750 draft.forEach(item => {751 item.a += 10752 sum2 += item.a753 })754 expect(sum2).toBe(23)755 })756 expect(result).not.toBe(base)757 expect(base).toEqual(758 new Set([759 {id: 1, a: 1},760 {id: 2, a: 2}761 ])762 )763 expect(result).toEqual(764 new Set([765 {id: 1, a: 11},766 {id: 2, a: 12}767 ])768 )769 })770771 it("state stays the same if the same item is added", () => {772 const nextState = produce(baseState, s => {773 s.aSet.add("Luke")774 })775 expect(nextState).toBe(baseState)776 expect(nextState.aSet).toBe(baseState.aSet)777 })778779 it("can add new items", () => {780 const nextState = produce(baseState, s => {781 // Set.prototype.set should return the Set itself782 const res = s.aSet.add("force")783 if (!global.USES_BUILD) expect(res).toBe(s.aSet[DRAFT_STATE].draft)784 })785 expect(nextState).not.toBe(baseState)786 expect(nextState.aSet).not.toBe(baseState.aSet)787 expect(baseState.aSet.has("force")).toBe(false)788 expect(nextState.aSet.has("force")).toBe(true)789 })790791 it("returns 'size'", () => {792 const nextState = produce(baseState, s => {793 s.aSet.add("newKey")794 expect(s.aSet.size).toBe(baseState.aSet.size + 1)795 })796 expect(nextState).not.toBe(baseState)797 expect(nextState.aSet).not.toBe(baseState.aSet)798 expect(nextState.aSet.has("newKey")).toBe(true)799 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)800 })801802 it("can use 'delete' to remove items", () => {803 const nextState = produce(baseState, s => {804 expect(s.aSet.has("Luke")).toBe(true)805 expect(s.aSet.delete("Luke")).toBe(true)806 expect(s.aSet.delete("Luke")).toBe(false)807 expect(s.aSet.has("Luke")).toBe(false)808 })809 expect(nextState.aSet).not.toBe(baseState.aSet)810 expect(baseState.aSet.has("Luke")).toBe(true)811 expect(nextState.aSet.has("Luke")).toBe(false)812 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)813 })814815 it("can use 'clear' to remove items", () => {816 const nextState = produce(baseState, s => {817 expect(s.aSet.size).not.toBe(0)818 s.aSet.clear()819 expect(s.aSet.size).toBe(0)820 })821 expect(nextState.aSet).not.toBe(baseState.aSet)822 expect(baseState.aSet.size).not.toBe(0)823 expect(nextState.aSet.size).toBe(0)824 })825826 it("supports 'has'", () => {827 const nextState = produce(baseState, s => {828 expect(s.aSet.has("newKey")).toBe(false)829 s.aSet.add("newKey")830 expect(s.aSet.has("newKey")).toBe(true)831 })832 expect(nextState).not.toBe(baseState)833 expect(nextState.aSet).not.toBe(baseState.aSet)834 expect(baseState.aSet.has("newKey")).toBe(false)835 expect(nextState.aSet.has("newKey")).toBe(true)836 })837838 it("supports nested sets", () => {839 const base = new Set([new Set(["Serenity"])])840 const result = produce(base, draft => {841 draft.forEach(nestedItem => nestedItem.add("Firefly"))842 })843 expect(result).not.toBe(base)844 expect(base).toEqual(new Set([new Set(["Serenity"])]))845 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))846 })847848 it("supports has / delete on elements from the original", () => {849 const obj = {}850 const set = new Set([obj])851 const next = produce(set, d => {852 expect(d.has(obj)).toBe(true)853 d.add(3)854 expect(d.has(obj)).toBe(true)855 d.delete(obj)856 expect(d.has(obj)).toBe(false)857 })858 expect(next).toEqual(new Set([3]))859 })860861 it("revokes sets", () => {862 let m863 produce(baseState, s => {864 m = s.aSet865 })866 expect(() => m.has("x")).toThrow(867 "Cannot use a proxy that has been revoked"868 )869 expect(() => m.add("x")).toThrow(870 "Cannot use a proxy that has been revoked"871 )872 })873874 it("does support instanceof Set", () => {875 const set = new Set()876 produce(set, d => {877 expect(d instanceof Set).toBeTruthy()878 })879 })880 })881882 it("supports `immerable` symbol on constructor", () => {883 class One {}884 One[immerable] = true885 const baseState = new One()886 const nextState = produce(baseState, draft => {887 expect(draft).not.toBe(baseState)888 draft.foo = true889 })890 expect(nextState).not.toBe(baseState)891 expect(nextState.foo).toBeTruthy()892 })893894 it("preserves symbol properties", () => {895 const test = Symbol("test")896 const baseState = {[test]: true}897 const nextState = produce(baseState, s => {898 expect(s[test]).toBeTruthy()899 s.foo = true900 })901 expect(nextState).toEqual({902 [test]: true,903 foo: true904 })905 })906907 if (!global.USES_BUILD)908 it("preserves non-enumerable properties", () => {909 const baseState = {}910 // Non-enumerable object property911 Object.defineProperty(baseState, "foo", {912 value: {a: 1},913 enumerable: false914 })915 // Non-enumerable primitive property916 Object.defineProperty(baseState, "bar", {917 value: 1,918 enumerable: false919 })920 const nextState = produce(baseState, s => {921 expect(s.foo).toBeTruthy()922 expect(isEnumerable(s, "foo")).toBeFalsy()923 s.bar++924 expect(isEnumerable(s, "foo")).toBeFalsy()925 s.foo.a++926 expect(isEnumerable(s, "foo")).toBeFalsy()927 })928 expect(nextState.foo).toBeTruthy()929 expect(isEnumerable(nextState, "foo")).toBeFalsy()930 })931932 it("throws on computed properties", () => {933 const baseState = {}934 Object.defineProperty(baseState, "foo", {935 get: () => {},936 enumerable: true937 })938 expect(() => {939 produce(baseState, s => {940 // Proxies only throw once a change is made.941 if (useProxies) {942 s.modified = true943 }944 })945 }).toThrowErrorMatchingSnapshot()946 })947948 it("allows inherited computed properties", () => {949 const proto = {}950 Object.defineProperty(proto, "foo", {951 get() {952 return this.bar953 },954 set(val) {955 this.bar = val956 }957 })958 const baseState = Object.create(proto)959 produce(baseState, s => {960 expect(s.bar).toBeUndefined()961 s.foo = {}962 expect(s.bar).toBeDefined()963 expect(s.foo).toBe(s.bar)964 })965 })966967 it("supports a base state with multiple references to an object", () => {968 const obj = {}969 const res = produce({a: obj, b: obj}, d => {970 // Two drafts are created for each occurrence of an object in the base state.971 expect(d.a).not.toBe(d.b)972 d.a.z = true973 expect(d.b.z).toBeUndefined()974 })975 expect(res.b).toBe(obj)976 expect(res.a).not.toBe(res.b)977 expect(res.a.z).toBeTruthy()978 })979980 // NOTE: Except the root draft.981 it("supports multiple references to any modified draft", () => {982 const next = produce({a: {b: 1}}, d => {983 d.a.b++984 d.b = d.a985 })986 expect(next.a).toBe(next.b)987 })988989 it("can rename nested objects (no changes)", () => {990 const nextState = produce({obj: {}}, s => {991 s.foo = s.obj992 delete s.obj993 })994 expect(nextState).toEqual({foo: {}})995 })996997 // Very similar to the test before, but the reused object has one998 // property changed, one added, and one removed.999 it("can rename nested objects (with changes)", () => {1000 const nextState = produce({obj: {a: 1, b: 1}}, s => {1001 s.obj.a = true // change1002 delete s.obj.b // delete1003 s.obj.c = true // add10041005 s.foo = s.obj1006 delete s.obj1007 })1008 expect(nextState).toEqual({foo: {a: true, c: true}})1009 })10101011 it("can nest a draft in a new object (no changes)", () => {1012 const baseState = {obj: {}}1013 const nextState = produce(baseState, s => {1014 s.foo = {bar: s.obj}1015 delete s.obj1016 })1017 expect(nextState.foo.bar).toBe(baseState.obj)1018 })10191020 it("can nest a modified draft in a new object", () => {1021 const nextState = produce({obj: {a: 1, b: 1}}, s => {1022 s.obj.a = true // change1023 delete s.obj.b // delete1024 s.obj.c = true // add10251026 s.foo = {bar: s.obj}1027 delete s.obj1028 })1029 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1030 })10311032 it("supports assigning undefined to an existing property", () => {1033 const nextState = produce(baseState, s => {1034 s.aProp = undefined1035 })1036 expect(nextState).not.toBe(baseState)1037 expect(nextState.aProp).toBe(undefined)1038 })10391040 it("supports assigning undefined to a new property", () => {1041 const baseState = {}1042 const nextState = produce(baseState, s => {1043 s.aProp = undefined1044 })1045 expect(nextState).not.toBe(baseState)1046 expect(nextState.aProp).toBe(undefined)1047 })10481049 // NOTE: ES5 drafts only protect existing properties when revoked.1050 it("revokes the draft once produce returns", () => {1051 const expectRevoked = (fn, shouldThrow = true) => {1052 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()1053 else expect(fn).not.toThrow()1054 }10551056 // Test object drafts:1057 let draft1058 produce({a: 1, b: 1}, s => {1059 draft = s1060 delete s.b1061 })10621063 // Access known property on object draft.1064 expectRevoked(() => {1065 draft.a1066 })10671068 // Assign known property on object draft.1069 expectRevoked(() => {1070 draft.a = true1071 })10721073 // Access unknown property on object draft.1074 expectRevoked(() => {1075 draft.z1076 }, useProxies)10771078 // Assign unknown property on object draft.1079 expectRevoked(() => {1080 draft.z = true1081 }, useProxies)10821083 // Test array drafts:1084 produce([1, 2], s => {1085 draft = s1086 s.pop()1087 })10881089 // Access known index of an array draft.1090 expectRevoked(() => {1091 draft[0]1092 })10931094 // Assign known index of an array draft.1095 expectRevoked(() => {1096 draft[0] = true1097 })10981099 // Access unknown index of an array draft.1100 expectRevoked(() => {1101 draft[1]1102 }, useProxies)11031104 // Assign unknown index of an array draft.1105 expectRevoked(() => {1106 draft[1] = true1107 }, useProxies)1108 })11091110 it("can access a child draft that was created before the draft was modified", () => {1111 produce({a: {}}, s => {1112 const before = s.a1113 s.b = 11114 expect(s.a).toBe(before)1115 })1116 })11171118 it("should reflect all changes made in the draft immediately", () => {1119 produce(baseState, draft => {1120 draft.anArray[0] = 51121 draft.anArray.unshift("test")1122 if (!global.USES_BUILD)1123 expect(enumerableOnly(draft.anArray)).toEqual([1124 "test",1125 5,1126 2,1127 {c: 3},1128 11129 ])1130 draft.stuffz = "coffee"1131 expect(draft.stuffz).toBe("coffee")1132 })1133 })11341135 if (useProxies)1136 it("throws when Object.defineProperty() is used on drafts", () => {1137 expect(() => {1138 produce({}, draft => {1139 Object.defineProperty(draft, "xx", {1140 enumerable: true,1141 writeable: true,1142 value: 21143 })1144 })1145 }).toThrowErrorMatchingSnapshot()1146 })11471148 it("should handle constructor correctly", () => {1149 const baseState = {1150 arr: new Array(),1151 obj: new Object()1152 }1153 const result = produce(baseState, draft => {1154 draft.arrConstructed = draft.arr.constructor(1)1155 draft.objConstructed = draft.obj.constructor(1)1156 })1157 expect(result.arrConstructed).toEqual(new Array().constructor(1))1158 expect(result.objConstructed).toEqual(new Object().constructor(1))1159 })11601161 it("should handle equality correctly - 1", () => {1162 const baseState = {1163 y: 3 / 0,1164 z: NaN1165 }1166 const nextState = produce(baseState, draft => {1167 draft.y = 4 / 01168 draft.z = NaN1169 })1170 expect(nextState).toBe(baseState)1171 })11721173 it("should handle equality correctly - 2", () => {1174 const baseState = {1175 x: -01176 }1177 const nextState = produce(baseState, draft => {1178 draft.x = +01179 })1180 expect(nextState).not.toBe(baseState)1181 expect(nextState).not.toEqual(baseState)1182 })11831184 // AKA: recursive produce calls1185 describe("nested producers", () => {1186 describe("when base state is not a draft", () => {1187 // This test ensures the global state used to manage proxies is1188 // never left in a corrupted state by a nested `produce` call.1189 it("never affects its parent producer implicitly", () => {1190 const base = {obj: {a: 1}}1191 const next = produce(base, draft => {1192 // Notice how `base.obj` is passed, not `draft.obj`1193 const obj2 = produce(base.obj, draft2 => {1194 draft2.a = 01195 })1196 expect(obj2.a).toBe(0)1197 expect(draft.obj.a).toBe(1) // effects should not be visible outside1198 })1199 expect(next).toBe(base)1200 })1201 })12021203 describe("when base state is a draft", () => {1204 it("always wraps the draft in a new draft", () => {1205 produce({}, parent => {1206 produce(parent, child => {1207 expect(child).not.toBe(parent)1208 expect(isDraft(child)).toBeTruthy()1209 expect(original(child)).toBe(parent)1210 })1211 })1212 })12131214 // Reported by: https://github.com/mweststrate/immer/issues/3431215 it("ensures each property is drafted", () => {1216 produce({a: {}, b: {}}, parent => {1217 parent.a // Access "a" but not "b"1218 produce(parent, child => {1219 child.c = 11220 expect(isDraft(child.a)).toBeTruthy()1221 expect(isDraft(child.b)).toBeTruthy()1222 })1223 })1224 })12251226 it("preserves any pending changes", () => {1227 produce({a: 1, b: 1, d: 1}, parent => {1228 parent.b = 21229 parent.c = 21230 delete parent.d1231 produce(parent, child => {1232 expect(child.a).toBe(1) // unchanged1233 expect(child.b).toBe(2) // changed1234 expect(child.c).toBe(2) // added1235 expect(child.d).toBeUndefined() // deleted1236 })1237 })1238 })1239 })12401241 describe("when base state contains a draft", () => {1242 it("wraps unowned draft with its own draft", () => {1243 produce({a: {}}, parent => {1244 produce({a: parent.a}, child => {1245 expect(child.a).not.toBe(parent.a)1246 expect(isDraft(child.a)).toBeTruthy()1247 expect(original(child.a)).toBe(parent.a)1248 })1249 })1250 })12511252 it("returns unowned draft if no changes were made", () => {1253 produce({a: {}}, parent => {1254 const result = produce({a: parent.a}, () => {})1255 expect(result.a).toBe(parent.a)1256 })1257 })12581259 it("clones the unowned draft when changes are made", () => {1260 produce({a: {}}, parent => {1261 const result = produce({a: parent.a}, child => {1262 child.a.b = 11263 })1264 expect(result.a).not.toBe(parent.a)1265 expect(result.a.b).toBe(1)1266 expect("b" in parent.a).toBeFalsy()1267 })1268 })12691270 // We cannot auto-freeze the result of a nested producer,1271 // because it may contain a draft from a parent producer.1272 it("never auto-freezes the result", () => {1273 produce({a: {}}, parent => {1274 const r = produce({a: parent.a}, child => {1275 child.b = 1 // Ensure a copy is returned.1276 })1277 expect(Object.isFrozen(r)).toBeFalsy()1278 })1279 })1280 })12811282 // "Upvalues" are variables from a parent scope.1283 it("does not finalize upvalue drafts", () => {1284 produce({a: {}, b: {}}, parent => {1285 expect(produce({}, () => parent)).toBe(parent)1286 parent.x // Ensure proxy not revoked.12871288 expect(produce({}, () => [parent])[0]).toBe(parent)1289 parent.x // Ensure proxy not revoked.12901291 expect(produce({}, () => parent.a)).toBe(parent.a)1292 parent.a.x // Ensure proxy not revoked.12931294 // Modified parent test1295 parent.c = 11296 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1297 parent.b.x // Ensure proxy not revoked.1298 })1299 })13001301 it("works with interweaved Immer instances", () => {1302 const options = {useProxies, autoFreeze}1303 const one = createPatchedImmer(options)1304 const two = createPatchedImmer(options)13051306 const base = {}1307 const result = one.produce(base, s1 =>1308 two.produce({s1}, s2 => {1309 expect(original(s2.s1)).toBe(s1)1310 s2.n = 11311 s2.s1 = one.produce({s2}, s3 => {1312 expect(original(s3.s2)).toBe(s2)1313 expect(original(s3.s2.s1)).toBe(s2.s1)1314 return s3.s2.s11315 })1316 })1317 )1318 expect(result.n).toBe(1)1319 expect(result.s1).toBe(base)1320 })1321 })13221323 if (useProxies)1324 it("throws when Object.setPrototypeOf() is used on a draft", () => {1325 produce({}, draft => {1326 expect(() =>1327 Object.setPrototypeOf(draft, Array)1328 ).toThrowErrorMatchingSnapshot()1329 })1330 })13311332 it("supports the 'in' operator", () => {1333 produce(baseState, draft => {1334 // Known property1335 expect("anArray" in draft).toBe(true)1336 expect(Reflect.has(draft, "anArray")).toBe(true)13371338 // Unknown property1339 expect("bla" in draft).toBe(false)1340 expect(Reflect.has(draft, "bla")).toBe(false)13411342 // Known index1343 expect(0 in draft.anArray).toBe(true)1344 expect("0" in draft.anArray).toBe(true)1345 expect(Reflect.has(draft.anArray, 0)).toBe(true)1346 expect(Reflect.has(draft.anArray, "0")).toBe(true)13471348 // Unknown index1349 expect(17 in draft.anArray).toBe(false)1350 expect("17" in draft.anArray).toBe(false)1351 expect(Reflect.has(draft.anArray, 17)).toBe(false)1352 expect(Reflect.has(draft.anArray, "17")).toBe(false)1353 })1354 })13551356 it("'this' should not be bound anymore - 1", () => {1357 const base = {x: 3}1358 const next1 = produce(base, function() {1359 expect(this).toBe(undefined)1360 })1361 })13621363 it("'this' should not be bound anymore - 2", () => {1364 const incrementor = produce(function() {1365 expect(this).toBe(undefined)1366 })1367 incrementor()1368 })13691370 it("should be possible to use dynamic bound this", () => {1371 const world = {1372 counter: {count: 1},1373 inc: produce(function(draft) {1374 expect(this).toBe(world)1375 draft.counter.count = this.counter.count + 11376 })1377 }13781379 expect(world.inc(world).counter.count).toBe(2)1380 })13811382 // See here: https://github.com/mweststrate/immer/issues/891383 it("supports the spread operator", () => {1384 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1385 const result = produce(base, draft => {1386 draft.foo = {x: 1, ...draft.foo, y: 1}1387 draft.bar = [1, ...draft.bar, 1]1388 })1389 expect(result).toEqual({1390 foo: {x: 0, y: 1},1391 bar: [1, 0, 0, 1]1392 })1393 })13941395 it("processes with lodash.set", () => {1396 const base = [{id: 1, a: 1}]1397 const result = produce(base, draft => {1398 lodash.set(draft, "[0].a", 2)1399 })1400 expect(base[0].a).toEqual(1)1401 expect(result[0].a).toEqual(2)1402 })14031404 it("processes with lodash.find", () => {1405 const base = [{id: 1, a: 1}]1406 const result = produce(base, draft => {1407 const obj1 = lodash.find(draft, {id: 1})1408 lodash.set(obj1, "a", 2)1409 })1410 expect(base[0].a).toEqual(1)1411 expect(result[0].a).toEqual(2)1412 })14131414 it("does not draft external data", () => {1415 const externalData = {x: 3}1416 const base = {}1417 const next = produce(base, draft => {1418 // potentially, we *could* draft external data automatically, but only if those statements are not switched...1419 draft.y = externalData1420 draft.y.x += 11421 externalData.x += 11422 })1423 expect(next).toEqual({y: {x: 5}})1424 expect(externalData.x).toBe(5)1425 expect(next.y).toBe(externalData)1426 })14271428 it("does not create new state unnecessary, #491", () => {1429 const a = {highlight: true}1430 const next1 = produce(a, draft => {1431 draft.highlight = false1432 draft.highlight = true1433 })1434 // See explanation in issue1435 expect(next1).not.toBe(a)14361437 const next2 = produce(a, draft => {1438 draft.highlight = true1439 })1440 expect(next2).toBe(a)1441 })14421443 autoFreeze &&1444 test.skip("issue #462 - frozen", () => {1445 var origin = {1446 a: {1447 value: "no"1448 },1449 b: {1450 value: "no"1451 }1452 }1453 var im = produce(origin, origin => {1454 origin.a.value = "im"1455 })1456 expect(() => (origin.b.value = "yes")).toThrow() // should throw!1457 // to prevent this...:1458 // expect(im.b.value).toBe('no');1459 })14601461 autoFreeze &&1462 test("issue #469, state not frozen", () => {1463 const project = produce(1464 {1465 id: 1,1466 tracks: [{id: 1}]1467 },1468 () => {}1469 )14701471 expect(() => {1472 project.id = 2 // Does not throw error1473 }).toThrowError("Cannot assign to read only property 'id'")14741475 expect(() => {1476 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1477 }).toThrowError("Cannot assign to read only property 'id'")1478 })14791480 describe("recipe functions", () => {1481 it("can return a new object", () => {1482 const base = {x: 3}1483 const res = produce(base, d => {1484 return {x: d.x + 1}1485 })1486 expect(res).not.toBe(base)1487 expect(res).toEqual({x: 4})1488 })14891490 it("can return the draft", () => {1491 const base = {x: 3}1492 const res = produce(base, d => {1493 d.x = 41494 return d1495 })1496 expect(res).not.toBe(base)1497 expect(res).toEqual({x: 4})1498 })14991500 it("can return an unmodified child draft", () => {1501 const base = {a: {}}1502 const res = produce(base, d => {1503 return d.a1504 })1505 expect(res).toBe(base.a)1506 })15071508 // TODO: Avoid throwing if only the child draft was modified.1509 it("cannot return a modified child draft", () => {1510 const base = {a: {}}1511 expect(() => {1512 produce(base, d => {1513 d.a.b = 11514 return d.a1515 })1516 }).toThrowErrorMatchingSnapshot()1517 })15181519 it("can return a frozen object", () => {1520 const res = deepFreeze([{x: 3}])1521 expect(produce({}, () => res)).toBe(res)1522 })15231524 it("can return an object with two references to another object", () => {1525 const next = produce({}, d => {1526 const obj = {}1527 return {obj, arr: [obj]}1528 })1529 expect(next.obj).toBe(next.arr[0])1530 })15311532 it("can return an object with two references to an unmodified draft", () => {1533 const base = {a: {}}1534 const next = produce(base, d => {1535 return [d.a, d.a]1536 })1537 expect(next[0]).toBe(base.a)1538 expect(next[0]).toBe(next[1])1539 })15401541 it("cannot return an object that references itself", () => {1542 const res = {}1543 res.self = res1544 expect(() => {1545 produce(res, () => res.self)1546 }).toThrowErrorMatchingSnapshot()1547 })1548 })15491550 describe("async recipe function", () => {1551 it("can modify the draft", () => {1552 const base = {a: 0, b: 0}1553 return produce(base, async d => {1554 d.a = 11555 await Promise.resolve()1556 d.b = 11557 }).then(res => {1558 expect(res).not.toBe(base)1559 expect(res).toEqual({a: 1, b: 1})1560 })1561 })15621563 it("works with rejected promises", () => {1564 let draft1565 const base = {a: 0, b: 0}1566 const err = new Error("passed")1567 return produce(base, d => {1568 draft = d1569 draft.b = 11570 return Promise.reject(err)1571 }).then(1572 () => {1573 throw "failed"1574 },1575 e => {1576 expect(e).toBe(err)1577 expect(() => draft.a).toThrowErrorMatchingSnapshot()1578 }1579 )1580 })15811582 it("supports recursive produce calls after await", () => {1583 const base = {obj: {k: 1}}1584 return produce(base, d => {1585 const obj = d.obj1586 delete d.obj1587 return Promise.resolve().then(() => {1588 d.a = produce({}, d => {1589 d.b = obj // Assign a draft owned by the parent scope.1590 })15911592 // Auto-freezing is prevented when an unowned draft exists.1593 expect(Object.isFrozen(d.a)).toBeFalsy()15941595 // Ensure `obj` is not revoked.1596 obj.c = 11597 })1598 }).then(res => {1599 expect(res).not.toBe(base)1600 expect(res).toEqual({1601 a: {b: {k: 1, c: 1}}1602 })1603 })1604 })1605 })16061607 it("throws when the draft is modified and another object is returned", () => {1608 const base = {x: 3}1609 expect(() => {1610 produce(base, draft => {1611 draft.x = 41612 return {x: 5}1613 })1614 }).toThrowErrorMatchingSnapshot()1615 })16161617 it("should fix #117 - 1", () => {1618 const reducer = (state, action) =>1619 produce(state, draft => {1620 switch (action.type) {1621 case "SET_STARTING_DOTS":1622 return draft.availableStartingDots.map(a => a)1623 default:1624 break1625 }1626 })1627 const base = {1628 availableStartingDots: [1629 {dots: 4, count: 1},1630 {dots: 3, count: 2},1631 {dots: 2, count: 3},1632 {dots: 1, count: 4}1633 ]1634 }1635 const next = reducer(base, {type: "SET_STARTING_DOTS"})1636 expect(next).toEqual(base.availableStartingDots)1637 expect(next).not.toBe(base.availableStartingDots)1638 })16391640 it("should fix #117 - 2", () => {1641 const reducer = (state, action) =>1642 produce(state, draft => {1643 switch (action.type) {1644 case "SET_STARTING_DOTS":1645 return {1646 dots: draft.availableStartingDots.map(a => a)1647 }1648 default:1649 break1650 }1651 })1652 const base = {1653 availableStartingDots: [1654 {dots: 4, count: 1},1655 {dots: 3, count: 2},1656 {dots: 2, count: 3},1657 {dots: 1, count: 4}1658 ]1659 }1660 const next = reducer(base, {type: "SET_STARTING_DOTS"})1661 expect(next).toEqual({dots: base.availableStartingDots})1662 })16631664 it("cannot always detect noop assignments - 0", () => {1665 const baseState = {x: {y: 3}}1666 const nextState = produce(baseState, d => {1667 const a = d.x1668 d.x = a1669 })1670 expect(nextState).toBe(baseState)1671 })16721673 it("cannot always detect noop assignments - 1", () => {1674 const baseState = {x: {y: 3}}1675 const nextState = produce(baseState, d => {1676 const a = d.x1677 d.x = 41678 d.x = a1679 })1680 // Ideally, this should actually be the same instances1681 // but this would be pretty expensive to detect,1682 // so we don't atm1683 expect(nextState).not.toBe(baseState)1684 })16851686 it("cannot always detect noop assignments - 2", () => {1687 const baseState = {x: {y: 3}}1688 const nextState = produce(baseState, d => {1689 const a = d.x1690 const stuff = a.y + 31691 d.x = 41692 d.x = a1693 })1694 // Ideally, this should actually be the same instances1695 // but this would be pretty expensive to detect,1696 // so we don't atm1697 expect(nextState).not.toBe(baseState)1698 })16991700 it("cannot always detect noop assignments - 3", () => {1701 const baseState = {x: 3}1702 const nextState = produce(baseState, d => {1703 d.x = 31704 })1705 expect(nextState).toBe(baseState)1706 })17071708 it("cannot always detect noop assignments - 4", () => {1709 const baseState = {x: 3}1710 const nextState = produce(baseState, d => {1711 d.x = 41712 d.x = 31713 })1714 // Ideally, this should actually be the same instances1715 // but this would be pretty expensive to detect,1716 // so we don't atm1717 expect(nextState).not.toBe(baseState)1718 })17191720 it("cannot produce undefined by returning undefined", () => {1721 const base = 31722 expect(produce(base, () => 4)).toBe(4)1723 expect(produce(base, () => null)).toBe(null)1724 expect(produce(base, () => undefined)).toBe(3)1725 expect(produce(base, () => {})).toBe(3)1726 expect(produce(base, () => nothing)).toBe(undefined)17271728 expect(produce({}, () => undefined)).toEqual({})1729 expect(produce({}, () => nothing)).toBe(undefined)1730 expect(produce(3, () => nothing)).toBe(undefined)17311732 expect(produce(() => undefined)({})).toEqual({})1733 expect(produce(() => nothing)({})).toBe(undefined)1734 expect(produce(() => nothing)(3)).toBe(undefined)1735 })17361737 describe("base state type", () => {1738 if (!global.USES_BUILD) testObjectTypes(produce)1739 testLiteralTypes(produce)1740 })17411742 afterEach(() => {1743 expect(baseState).toBe(origBaseState)1744 expect(baseState).toEqual(createBaseState())1745 })17461747 class Foo {}1748 function createBaseState() {1749 const data = {1750 anInstance: new Foo(),1751 anArray: [3, 2, {c: 3}, 1],1752 aMap: new Map([1753 ["jedi", {name: "Luke", skill: 10}],1754 ["jediTotal", 42],1755 ["force", "these aren't the droids you're looking for"]1756 ]),1757 aSet: new Set([1758 "Luke",1759 42,1760 {1761 jedi: "Yoda"1762 }1763 ]),1764 aProp: "hi",1765 anObject: {1766 nested: {1767 yummie: true1768 },1769 coffee: false1770 }1771 }1772 return autoFreeze ? deepFreeze(data) : data1773 }1774 })17751776 describe(`isDraft - ${name}`, () => {1777 it("returns true for object drafts", () => {1778 produce({}, state => {1779 expect(isDraft(state)).toBeTruthy()1780 })1781 })1782 it("returns true for array drafts", () => {1783 produce([], state => {1784 expect(isDraft(state)).toBeTruthy()1785 })1786 })1787 it("returns true for objects nested in object drafts", () => {1788 produce({a: {b: {}}}, state => {1789 expect(isDraft(state.a)).toBeTruthy()1790 expect(isDraft(state.a.b)).toBeTruthy()1791 })1792 })1793 it("returns false for new objects added to a draft", () => {1794 produce({}, state => {1795 state.a = {}1796 expect(isDraft(state.a)).toBeFalsy()1797 })1798 })1799 it("returns false for objects returned by the producer", () => {1800 const object = produce(null, Object.create)1801 expect(isDraft(object)).toBeFalsy()1802 })1803 it("returns false for arrays returned by the producer", () => {1804 const array = produce(null, _ => [])1805 expect(isDraft(array)).toBeFalsy()1806 })1807 it("returns false for object drafts returned by the producer", () => {1808 const object = produce({}, state => state)1809 expect(isDraft(object)).toBeFalsy()1810 })1811 it("returns false for array drafts returned by the producer", () => {1812 const array = produce([], state => state)1813 expect(isDraft(array)).toBeFalsy()1814 })1815 })18161817 describe(`complex nesting map / set / object`, () => {1818 const a = {a: 1}1819 const b = {b: 2}1820 const c = {c: 3}1821 const set1 = new Set([a, b])1822 const set2 = new Set([c])1823 const map = new Map([1824 ["set1", set1],1825 ["set2", set2]1826 ])1827 const base = {map}18281829 function first(set) {1830 return Array.from(set.values())[0]1831 }18321833 function second(set) {1834 return Array.from(set.values())[1]1835 }18361837 test(`modify deep object`, () => {1838 const [res, patches] = produceWithPatches(base, draft => {1839 const v = first(draft.map.get("set1"))1840 expect(original(v)).toBe(a)1841 expect(v).toEqual(a)1842 expect(v).not.toBe(a)1843 v.a++1844 })1845 expect(res).toMatchSnapshot()1846 expect(patches).toMatchSnapshot()1847 expect(a.a).toBe(1)1848 expect(base.map.get("set1")).toBe(set1)1849 expect(first(base.map.get("set1"))).toBe(a)1850 expect(res).not.toBe(base)1851 expect(res.map).not.toBe(base.map)1852 expect(res.map.get("set1")).not.toBe(base.map.get("set1"))1853 expect(second(base.map.get("set1"))).toBe(b)1854 expect(base.map.get("set2")).toBe(set2)1855 expect(first(res.map.get("set1"))).toEqual({a: 2})1856 })18571858 test(`modify deep object - keep value`, () => {1859 const [res, patches] = produceWithPatches(base, draft => {1860 const v = first(draft.map.get("set1"))1861 expect(original(v)).toBe(a)1862 expect(v).toEqual(a)1863 expect(v).not.toBe(a)1864 v.a = 1 // same value1865 })1866 expect(a.a).toBe(1)1867 expect(base.map.get("set1")).toBe(set1)1868 expect(first(base.map.get("set1"))).toBe(a)1869 expect(res).toBe(base)1870 expect(res.map).toBe(base.map)1871 expect(res.map.get("set1")).toBe(base.map.get("set1"))1872 expect(first(res.map.get("set1"))).toBe(a)1873 expect(second(base.map.get("set1"))).toBe(b)1874 expect(base.map.get("set2")).toBe(set2)1875 expect(patches.length).toBe(0)1876 })1877 })1878}18791880function testObjectTypes(produce) {1881 class Foo {1882 constructor(foo) {1883 this.foo = foo1884 this[immerable] = true1885 }1886 }1887 const values = {1888 "empty object": {},1889 "plain object": {a: 1, b: 2},1890 "object (no prototype)": Object.create(null),1891 "empty array": [],1892 "plain array": [1, 2],1893 "class instance (draftable)": new Foo(1)1894 }1895 for (const name in values) {1896 const value = values[name]1897 const copy = shallowCopy(value)1898 testObjectType(name, value)1899 testObjectType(name + " (frozen)", Object.freeze(copy))1900 }1901 function testObjectType(name, base) {1902 describe(name, () => {1903 it("creates a draft", () => {1904 produce(base, draft => {1905 expect(draft).not.toBe(base)1906 expect(shallowCopy(draft, true)).toEqual(base)1907 })1908 })19091910 it("preserves the prototype", () => {1911 const proto = Object.getPrototypeOf(base)1912 produce(base, draft => {1913 expect(Object.getPrototypeOf(draft)).toBe(proto)1914 })1915 })19161917 it("returns the base state when no changes are made", () => {1918 expect(produce(base, () => {})).toBe(base)1919 })19201921 it("returns a copy when changes are made", () => {1922 const random = Math.random()1923 const result = produce(base, draft => {1924 draft[0] = random1925 })1926 expect(result).not.toBe(base)1927 expect(result.constructor).toBe(base.constructor)1928 expect(result[0]).toBe(random)1929 })1930 })1931 }1932}19331934function testLiteralTypes(produce) {1935 class Foo {}1936 const values = {1937 "falsy number": 0,1938 "truthy number": 1,1939 "negative number": -1,1940 NaN: NaN,1941 infinity: 1 / 0,1942 true: true,1943 false: false,1944 "empty string": "",1945 "truthy string": "1",1946 null: null,1947 undefined: undefined,19481949 /**1950 * These objects are treated as literals because Immer1951 * does not know how to draft them.1952 */1953 function: () => {},1954 "regexp object": /.+/g,1955 "boxed number": new Number(0),1956 "boxed string": new String(""),1957 "boxed boolean": new Boolean(),1958 "date object": new Date(),1959 "class instance (not draftable)": new Foo()1960 }1961 for (const name in values) {1962 describe(name, () => {1963 const value = values[name]19641965 it("does not create a draft", () => {1966 produce(value, draft => {1967 expect(draft).toBe(value)1968 })1969 })19701971 it("returns the base state when no changes are made", () => {1972 expect(produce(value, () => {})).toBe(value)1973 })19741975 if (value && typeof value == "object") {1976 it("does not return a copy when changes are made", () => {1977 expect(1978 produce(value, draft => {1979 draft.foo = true1980 })1981 ).toBe(value)1982 })1983 }1984 })1985 }1986}19871988function enumerableOnly(x) {1989 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1990 each(copy, (prop, value) => {1991 if (value && typeof value === "object") {1992 copy[prop] = enumerableOnly(value)1993 }1994 })1995 return copy1996}