base.js
This file
Path
__tests__/base.js
1,793 lines · 48.5 KiB · JavaScript
Last changed by
fixed remaining tests, fixes #466Michel Weststratebefore adoption7f5e301
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/common"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 = [{id: 1, a: 1}, {id: 2, a: 1}]192 const findById = (collection, id) => {193 for (const item of collection) {194 if (item.id === id) return item195 }196 return null197 }198 const result = produce(base, draft => {199 const obj1 = findById(draft, 1)200 const obj2 = findById(draft, 2)201 obj1.a = 2202 obj2.a = 2203 })204 expect(result[0].a).toEqual(2)205 expect(result[1].a).toEqual(2)206 })207208 it("can assign an index via bracket notation", () => {209 const nextState = produce(baseState, s => {210 s.anArray[3] = true211 })212 expect(nextState).not.toBe(baseState)213 expect(nextState.anArray).not.toBe(baseState.anArray)214 expect(nextState.anArray[3]).toEqual(true)215 })216217 it("can use splice() to both add and remove items", () => {218 const nextState = produce(baseState, s => {219 s.anArray.splice(1, 1, "a", "b")220 })221 expect(nextState.anArray).not.toBe(baseState.anArray)222 expect(nextState.anArray[1]).toBe("a")223 expect(nextState.anArray[2]).toBe("b")224 })225226 it("can truncate via the length property", () => {227 const baseLength = baseState.anArray.length228 const nextState = produce(baseState, s => {229 s.anArray.length = baseLength - 1230 })231 expect(nextState.anArray).not.toBe(baseState.anArray)232 expect(nextState.anArray.length).toBe(baseLength - 1)233 })234235 it("can extend via the length property", () => {236 const baseLength = baseState.anArray.length237 const nextState = produce(baseState, s => {238 s.anArray.length = baseLength + 1239 })240 expect(nextState.anArray).not.toBe(baseState.anArray)241 expect(nextState.anArray.length).toBe(baseLength + 1)242 })243244 // Reported here: https://github.com/mweststrate/immer/issues/116245 it("can pop then push", () => {246 const nextState = produce([1, 2, 3], s => {247 s.pop()248 s.push(100)249 })250 expect(nextState).toEqual([1, 2, 100])251 })252253 it("can be sorted", () => {254 const baseState = [3, 1, 2]255 const nextState = produce(baseState, s => {256 s.sort()257 })258 expect(nextState).not.toBe(baseState)259 expect(nextState).toEqual([1, 2, 3])260 })261262 it("supports modifying nested objects", () => {263 const baseState = [{a: 1}, {}]264 const nextState = produce(baseState, s => {265 s[0].a++266 s[1].a = 0267 })268 expect(nextState).not.toBe(baseState)269 expect(nextState[0].a).toBe(2)270 expect(nextState[1].a).toBe(0)271 })272273 it("never preserves non-numeric properties", () => {274 const baseState = []275 baseState.x = 7276 const nextState = produce(baseState, s => {277 s.push(3)278 })279 expect("x" in nextState).toBeFalsy()280 })281282 if (useProxies) {283 it("throws when a non-numeric property is added", () => {284 expect(() => {285 produce([], d => {286 d.x = 3287 })288 }).toThrowErrorMatchingSnapshot()289 })290291 it("throws when a non-numeric property is deleted", () => {292 expect(() => {293 const baseState = []294 baseState.x = 7295 produce(baseState, d => {296 delete d.x297 })298 }).toThrowErrorMatchingSnapshot()299 })300 }301 })302303 describe("map drafts", () => {304 it("supports key access", () => {305 const value = baseState.aMap.get("jedi")306 const nextState = produce(baseState, s => {307 expect(s.aMap.get("jedi")).toEqual(value)308 })309 expect(nextState).toBe(baseState)310 })311312 it("supports key access for non-primitive keys", () => {313 const key = {prop: "val"}314 const base = new Map([[key, {id: 1, a: 1}]])315 const value = base.get(key)316 const nextState = produce(base, s => {317 expect(s.get(key)).toEqual(value)318 })319 expect(nextState).toBe(base)320 })321322 it("supports iteration", () => {323 const base = new Map([324 ["first", {id: 1, a: 1}],325 ["second", {id: 2, a: 1}]326 ])327 const findById = (map, id) => {328 for (const [, item] of map) {329 if (item.id === id) return item330 }331 return null332 }333 const result = produce(base, draft => {334 const obj1 = findById(draft, 1)335 const obj2 = findById(draft, 2)336 obj1.a = 2337 obj2.a = 2338 })339 expect(result).not.toBe(base)340 expect(result.get("first").a).toEqual(2)341 expect(result.get("second").a).toEqual(2)342 })343344 it("supports 'entries'", () => {345 const base = new Map([346 ["first", {id: 1, a: 1}],347 ["second", {id: 2, a: 1}]348 ])349 const findById = (map, id) => {350 for (const [, item] of map.entries()) {351 if (item.id === id) return item352 }353 return null354 }355 const result = produce(base, draft => {356 const obj1 = findById(draft, 1)357 const obj2 = findById(draft, 2)358 obj1.a = 2359 obj2.a = 2360 })361 expect(result).not.toBe(base)362 expect(result.get("first").a).toEqual(2)363 expect(result.get("second").a).toEqual(2)364 })365366 it("supports 'values'", () => {367 const base = new Map([368 ["first", {id: 1, a: 1}],369 ["second", {id: 2, a: 1}]370 ])371 const findById = (map, id) => {372 for (const item of map.values()) {373 if (item.id === id) return item374 }375 return null376 }377 const result = produce(base, draft => {378 const obj1 = findById(draft, 1)379 const obj2 = findById(draft, 2)380 obj1.a = 2381 obj2.a = 2382 })383 expect(result).not.toBe(base)384 expect(result.get("first").a).toEqual(2)385 expect(result.get("second").a).toEqual(2)386 })387388 it("supports 'keys", () => {389 const base = new Map([["first", Symbol()], ["second", Symbol()]])390 const result = produce(base, draft => {391 expect([...draft.keys()]).toEqual(["first", "second"])392 draft.set("third", Symbol())393 expect([...draft.keys()]).toEqual(["first", "second", "third"])394 })395 })396397 it("supports forEach", () => {398 const key1 = {prop: "val1"}399 const key2 = {prop: "val2"}400 const base = new Map([401 ["first", {id: 1, a: 1}],402 ["second", {id: 2, a: 1}],403 [key1, {id: 3, a: 1}],404 [key2, {id: 4, a: 1}]405 ])406 const result = produce(base, draft => {407 let sum1 = 0408 draft.forEach(({a}) => {409 sum1 += a410 })411 expect(sum1).toBe(4)412 let sum2 = 0413 draft.get("first").a = 10414 draft.get("second").a = 20415 draft.get(key1).a = 30416 draft.get(key2).a = 40417 draft.forEach(({a}) => {418 sum2 += a419 })420 expect(sum2).toBe(100)421 })422 expect(result).not.toBe(base)423 expect(base.get("first").a).toEqual(1)424 expect(base.get("second").a).toEqual(1)425 expect(base.get(key1).a).toEqual(1)426 expect(base.get(key2).a).toEqual(1)427 expect(result.get("first").a).toEqual(10)428 expect(result.get("second").a).toEqual(20)429 expect(result.get(key1).a).toEqual(30)430 expect(result.get(key2).a).toEqual(40)431 })432433 it("supports forEach mutation", () => {434 const base = new Map([435 ["first", {id: 1, a: 1}],436 ["second", {id: 2, a: 1}]437 ])438 const result = produce(base, draft => {439 draft.forEach(item => {440 item.a = 100441 })442 })443 expect(result).not.toBe(base)444 expect(result.get("first").a).toEqual(100)445 expect(result.get("second").a).toEqual(100)446 })447448 it("can assign by key", () => {449 const nextState = produce(baseState, s => {450 // Map.prototype.set should return the Map itself451 const res = s.aMap.set("force", true)452 expect(res).toBe(s.aMap[DRAFT_STATE].draft)453 })454 expect(nextState).not.toBe(baseState)455 expect(nextState.aMap).not.toBe(baseState.aMap)456 expect(nextState.aMap.get("force")).toEqual(true)457 })458459 it("can assign by a non-primitive key", () => {460 const key = {prop: "val"}461 const value = {id: 1, a: 1}462 const base = new Map([[key, value]])463 const nextState = produce(base, s => {464 s.set(key, true)465 })466 expect(nextState).not.toBe(base)467 expect(base.get(key)).toEqual(value)468 expect(nextState.get(key)).toEqual(true)469 })470471 it("state stays the same if the the same item is assigned by key", () => {472 const nextState = produce(baseState, s => {473 s.aMap.set("jediTotal", 42)474 })475 expect(nextState).toBe(baseState)476 expect(nextState.aMap).toBe(baseState.aMap)477 })478479 it("returns 'size'", () => {480 const nextState = produce(baseState, s => {481 s.aMap.set("newKey", true)482 expect(s.aMap.size).toBe(baseState.aMap.size + 1)483 })484 expect(nextState).not.toBe(baseState)485 expect(nextState.aMap).not.toBe(baseState.aMap)486 expect(nextState.aMap.get("newKey")).toEqual(true)487 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)488 })489490 it("can use 'delete' to remove items", () => {491 const nextState = produce(baseState, s => {492 expect(s.aMap.has("jedi")).toBe(true)493 expect(s.aMap.delete("jedi")).toBe(true)494 expect(s.aMap.has("jedi")).toBe(false)495 })496 expect(nextState.aMap).not.toBe(baseState.aMap)497 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)498 expect(baseState.aMap.has("jedi")).toBe(true)499 expect(nextState.aMap.has("jedi")).toBe(false)500 })501502 it("can use 'clear' to remove items", () => {503 const nextState = produce(baseState, s => {504 expect(s.aMap.size).not.toBe(0)505 s.aMap.clear()506 expect(s.aMap.size).toBe(0)507 })508 expect(nextState.aMap).not.toBe(baseState.aMap)509 expect(baseState.aMap.size).not.toBe(0)510 expect(nextState.aMap.size).toBe(0)511 })512513 it("support 'has'", () => {514 const nextState = produce(baseState, s => {515 expect(s.aMap.has("newKey")).toBe(false)516 s.aMap.set("newKey", true)517 expect(s.aMap.has("newKey")).toBe(true)518 })519 expect(nextState).not.toBe(baseState)520 expect(nextState.aMap).not.toBe(baseState.aMap)521 expect(baseState.aMap.has("newKey")).toBe(false)522 expect(nextState.aMap.has("newKey")).toBe(true)523 })524525 it("supports nested maps", () => {526 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])527 const result = produce(base, draft => {528 draft.get("first").get("second").prop = "test1"529 })530 expect(result).not.toBe(base)531 expect(result.get("first")).not.toBe(base.get("first"))532 expect(result.get("first").get("second")).not.toBe(533 base.get("first").get("second")534 )535 expect(base.get("first").get("second").prop).toBe("test")536 expect(result.get("first").get("second").prop).toBe("test1")537 })538539 it("treats void deletes as no-op", () => {540 const base = new Map([["x", 1]])541 const next = produce(base, d => {542 expect(d.delete("y")).toBe(false)543 })544 expect(next).toBe(base)545 })546 })547548 describe("set drafts", () => {549 it("supports iteration", () => {550 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])551 const findById = (set, id) => {552 for (const item of set) {553 if (item.id === id) return item554 }555 return null556 }557 const result = produce(base, draft => {558 const obj1 = findById(draft, 1)559 const obj2 = findById(draft, 2)560 obj1.a = 2561 obj2.a = 2562 })563 expect(result).not.toBe(base)564 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))565 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))566 })567568 it("supports 'entries'", () => {569 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])570 const findById = (set, id) => {571 for (const [item1, item2] of set.entries()) {572 expect(item1).toBe(item2)573 if (item1.id === id) return item1574 }575 return null576 }577 const result = produce(base, draft => {578 const obj1 = findById(draft, 1)579 const obj2 = findById(draft, 2)580 obj1.a = 2581 obj2.a = 2582 })583 expect(result).not.toBe(base)584 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))585 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))586 })587588 it("supports 'values'", () => {589 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])590 const findById = (set, id) => {591 for (const item of set.values()) {592 if (item.id === id) return item593 }594 return null595 }596 const result = produce(base, draft => {597 const obj1 = findById(draft, 1)598 const obj2 = findById(draft, 2)599 obj1.a = 2600 obj2.a = 2601 })602 expect(result).not.toBe(base)603 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))604 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))605 })606607 it("supports 'keys'", () => {608 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])609 const findById = (set, id) => {610 for (const item of set.keys()) {611 if (item.id === id) return item612 }613 return null614 }615 const result = produce(base, draft => {616 const obj1 = findById(draft, 1)617 const obj2 = findById(draft, 2)618 obj1.a = 2619 obj2.a = 2620 })621 expect(result).not.toBe(base)622 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))623 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))624 })625626 it("supports forEach with mutation after reads", () => {627 const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])628 const result = produce(base, draft => {629 let sum1 = 0630 draft.forEach(({a}) => {631 sum1 += a632 })633 expect(sum1).toBe(3)634 let sum2 = 0635 draft.forEach(item => {636 item.a += 10637 sum2 += item.a638 })639 expect(sum2).toBe(23)640 })641 expect(result).not.toBe(base)642 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 2}]))643 expect(result).toEqual(new Set([{id: 1, a: 11}, {id: 2, a: 12}]))644 })645646 it("state stays the same if the same item is added", () => {647 const nextState = produce(baseState, s => {648 s.aSet.add("Luke")649 })650 expect(nextState).toBe(baseState)651 expect(nextState.aSet).toBe(baseState.aSet)652 })653654 it("can add new items", () => {655 const nextState = produce(baseState, s => {656 // Set.prototype.set should return the Set itself657 const res = s.aSet.add("force")658 expect(res).toBe(s.aSet[DRAFT_STATE].draft)659 })660 expect(nextState).not.toBe(baseState)661 expect(nextState.aSet).not.toBe(baseState.aSet)662 expect(baseState.aSet.has("force")).toBe(false)663 expect(nextState.aSet.has("force")).toBe(true)664 })665666 it("returns 'size'", () => {667 const nextState = produce(baseState, s => {668 s.aSet.add("newKey")669 expect(s.aSet.size).toBe(baseState.aSet.size + 1)670 })671 expect(nextState).not.toBe(baseState)672 expect(nextState.aSet).not.toBe(baseState.aSet)673 expect(nextState.aSet.has("newKey")).toBe(true)674 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)675 })676677 it("can use 'delete' to remove items", () => {678 const nextState = produce(baseState, s => {679 expect(s.aSet.has("Luke")).toBe(true)680 expect(s.aSet.delete("Luke")).toBe(true)681 expect(s.aSet.delete("Luke")).toBe(false)682 expect(s.aSet.has("Luke")).toBe(false)683 })684 expect(nextState.aSet).not.toBe(baseState.aSet)685 expect(baseState.aSet.has("Luke")).toBe(true)686 expect(nextState.aSet.has("Luke")).toBe(false)687 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)688 })689690 it("can use 'clear' to remove items", () => {691 const nextState = produce(baseState, s => {692 expect(s.aSet.size).not.toBe(0)693 s.aSet.clear()694 expect(s.aSet.size).toBe(0)695 })696 expect(nextState.aSet).not.toBe(baseState.aSet)697 expect(baseState.aSet.size).not.toBe(0)698 expect(nextState.aSet.size).toBe(0)699 })700701 it("supports 'has'", () => {702 const nextState = produce(baseState, s => {703 expect(s.aSet.has("newKey")).toBe(false)704 s.aSet.add("newKey")705 expect(s.aSet.has("newKey")).toBe(true)706 })707 expect(nextState).not.toBe(baseState)708 expect(nextState.aSet).not.toBe(baseState.aSet)709 expect(baseState.aSet.has("newKey")).toBe(false)710 expect(nextState.aSet.has("newKey")).toBe(true)711 })712713 it("supports nested sets", () => {714 const base = new Set([new Set(["Serenity"])])715 const result = produce(base, draft => {716 draft.forEach(nestedItem => nestedItem.add("Firefly"))717 })718 expect(result).not.toBe(base)719 expect(base).toEqual(new Set([new Set(["Serenity"])]))720 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))721 })722723 it("supports has / delete on elements from the original", () => {724 const obj = {}725 const set = new Set([obj])726 const next = produce(set, d => {727 expect(d.has(obj)).toBe(true)728 d.add(3)729 expect(d.has(obj)).toBe(true)730 d.delete(obj)731 expect(d.has(obj)).toBe(false)732 })733 expect(next).toEqual(new Set([3]))734 })735 })736737 it("supports `immerable` symbol on constructor", () => {738 class One {}739 One[immerable] = true740 const baseState = new One()741 const nextState = produce(baseState, draft => {742 expect(draft).not.toBe(baseState)743 draft.foo = true744 })745 expect(nextState).not.toBe(baseState)746 expect(nextState.foo).toBeTruthy()747 })748749 it("preserves symbol properties", () => {750 const test = Symbol("test")751 const baseState = {[test]: true}752 const nextState = produce(baseState, s => {753 expect(s[test]).toBeTruthy()754 s.foo = true755 })756 expect(nextState).toEqual({757 [test]: true,758 foo: true759 })760 })761762 it("preserves non-enumerable properties", () => {763 const baseState = {}764 // Non-enumerable object property765 Object.defineProperty(baseState, "foo", {766 value: {a: 1},767 enumerable: false768 })769 // Non-enumerable primitive property770 Object.defineProperty(baseState, "bar", {771 value: 1,772 enumerable: false773 })774 const nextState = produce(baseState, s => {775 expect(s.foo).toBeTruthy()776 expect(isEnumerable(s, "foo")).toBeFalsy()777 s.bar++778 expect(isEnumerable(s, "foo")).toBeFalsy()779 s.foo.a++780 expect(isEnumerable(s, "foo")).toBeFalsy()781 })782 expect(nextState.foo).toBeTruthy()783 expect(isEnumerable(nextState, "foo")).toBeFalsy()784 })785786 it("throws on computed properties", () => {787 const baseState = {}788 Object.defineProperty(baseState, "foo", {789 get: () => {},790 enumerable: true791 })792 expect(() => {793 produce(baseState, s => {794 // Proxies only throw once a change is made.795 if (useProxies) {796 s.modified = true797 }798 })799 }).toThrowErrorMatchingSnapshot()800 })801802 it("allows inherited computed properties", () => {803 const proto = {}804 Object.defineProperty(proto, "foo", {805 get() {806 return this.bar807 },808 set(val) {809 this.bar = val810 }811 })812 const baseState = Object.create(proto)813 produce(baseState, s => {814 expect(s.bar).toBeUndefined()815 s.foo = {}816 expect(s.bar).toBeDefined()817 expect(s.foo).toBe(s.bar)818 })819 })820821 it("supports a base state with multiple references to an object", () => {822 const obj = {}823 const res = produce({a: obj, b: obj}, d => {824 // Two drafts are created for each occurrence of an object in the base state.825 expect(d.a).not.toBe(d.b)826 d.a.z = true827 expect(d.b.z).toBeUndefined()828 })829 expect(res.b).toBe(obj)830 expect(res.a).not.toBe(res.b)831 expect(res.a.z).toBeTruthy()832 })833834 // NOTE: Except the root draft.835 it("supports multiple references to any modified draft", () => {836 const next = produce({a: {b: 1}}, d => {837 d.a.b++838 d.b = d.a839 })840 expect(next.a).toBe(next.b)841 })842843 it("can rename nested objects (no changes)", () => {844 const nextState = produce({obj: {}}, s => {845 s.foo = s.obj846 delete s.obj847 })848 expect(nextState).toEqual({foo: {}})849 })850851 // Very similar to the test before, but the reused object has one852 // property changed, one added, and one removed.853 it("can rename nested objects (with changes)", () => {854 const nextState = produce({obj: {a: 1, b: 1}}, s => {855 s.obj.a = true // change856 delete s.obj.b // delete857 s.obj.c = true // add858859 s.foo = s.obj860 delete s.obj861 })862 expect(nextState).toEqual({foo: {a: true, c: true}})863 })864865 it("can nest a draft in a new object (no changes)", () => {866 const baseState = {obj: {}}867 const nextState = produce(baseState, s => {868 s.foo = {bar: s.obj}869 delete s.obj870 })871 expect(nextState.foo.bar).toBe(baseState.obj)872 })873874 it("can nest a modified draft in a new object", () => {875 const nextState = produce({obj: {a: 1, b: 1}}, s => {876 s.obj.a = true // change877 delete s.obj.b // delete878 s.obj.c = true // add879880 s.foo = {bar: s.obj}881 delete s.obj882 })883 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})884 })885886 it("supports assigning undefined to an existing property", () => {887 const nextState = produce(baseState, s => {888 s.aProp = undefined889 })890 expect(nextState).not.toBe(baseState)891 expect(nextState.aProp).toBe(undefined)892 })893894 it("supports assigning undefined to a new property", () => {895 const baseState = {}896 const nextState = produce(baseState, s => {897 s.aProp = undefined898 })899 expect(nextState).not.toBe(baseState)900 expect(nextState.aProp).toBe(undefined)901 })902903 // NOTE: ES5 drafts only protect existing properties when revoked.904 it("revokes the draft once produce returns", () => {905 const expectRevoked = (fn, shouldThrow = true) => {906 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()907 else expect(fn).not.toThrow()908 }909910 // Test object drafts:911 let draft912 produce({a: 1, b: 1}, s => {913 draft = s914 delete s.b915 })916917 // Access known property on object draft.918 expectRevoked(() => {919 draft.a920 })921922 // Assign known property on object draft.923 expectRevoked(() => {924 draft.a = true925 })926927 // Access unknown property on object draft.928 expectRevoked(() => {929 draft.z930 }, useProxies)931932 // Assign unknown property on object draft.933 expectRevoked(() => {934 draft.z = true935 }, useProxies)936937 // Test array drafts:938 produce([1, 2], s => {939 draft = s940 s.pop()941 })942943 // Access known index of an array draft.944 expectRevoked(() => {945 draft[0]946 })947948 // Assign known index of an array draft.949 expectRevoked(() => {950 draft[0] = true951 })952953 // Access unknown index of an array draft.954 expectRevoked(() => {955 draft[1]956 }, useProxies)957958 // Assign unknown index of an array draft.959 expectRevoked(() => {960 draft[1] = true961 }, useProxies)962 })963964 it("can access a child draft that was created before the draft was modified", () => {965 produce({a: {}}, s => {966 const before = s.a967 s.b = 1968 expect(s.a).toBe(before)969 })970 })971972 it("should reflect all changes made in the draft immediately", () => {973 produce(baseState, draft => {974 draft.anArray[0] = 5975 draft.anArray.unshift("test")976 expect(enumerableOnly(draft.anArray)).toEqual(["test", 5, 2, {c: 3}, 1])977 draft.stuffz = "coffee"978 expect(draft.stuffz).toBe("coffee")979 })980 })981982 if (useProxies)983 it("throws when Object.defineProperty() is used on drafts", () => {984 expect(() => {985 produce({}, draft => {986 Object.defineProperty(draft, "xx", {987 enumerable: true,988 writeable: true,989 value: 2990 })991 })992 }).toThrowErrorMatchingSnapshot()993 })994995 it("should handle constructor correctly", () => {996 const baseState = {997 arr: new Array(),998 obj: new Object()999 }1000 const result = produce(baseState, draft => {1001 draft.arrConstructed = draft.arr.constructor(1)1002 draft.objConstructed = draft.obj.constructor(1)1003 })1004 expect(result.arrConstructed).toEqual(new Array().constructor(1))1005 expect(result.objConstructed).toEqual(new Object().constructor(1))1006 })10071008 it("should handle equality correctly - 1", () => {1009 const baseState = {1010 y: 3 / 0,1011 z: NaN1012 }1013 const nextState = produce(baseState, draft => {1014 draft.y = 4 / 01015 draft.z = NaN1016 })1017 expect(nextState).toBe(baseState)1018 })10191020 it("should handle equality correctly - 2", () => {1021 const baseState = {1022 x: -01023 }1024 const nextState = produce(baseState, draft => {1025 draft.x = +01026 })1027 expect(nextState).not.toBe(baseState)1028 expect(nextState).not.toEqual(baseState)1029 })10301031 // AKA: recursive produce calls1032 describe("nested producers", () => {1033 describe("when base state is not a draft", () => {1034 // This test ensures the global state used to manage proxies is1035 // never left in a corrupted state by a nested `produce` call.1036 it("never affects its parent producer implicitly", () => {1037 const base = {obj: {a: 1}}1038 const next = produce(base, draft => {1039 // Notice how `base.obj` is passed, not `draft.obj`1040 const obj2 = produce(base.obj, draft2 => {1041 draft2.a = 01042 })1043 expect(obj2.a).toBe(0)1044 expect(draft.obj.a).toBe(1) // effects should not be visible outside1045 })1046 expect(next).toBe(base)1047 })1048 })10491050 describe("when base state is a draft", () => {1051 it("always wraps the draft in a new draft", () => {1052 produce({}, parent => {1053 produce(parent, child => {1054 expect(child).not.toBe(parent)1055 expect(isDraft(child)).toBeTruthy()1056 expect(original(child)).toBe(parent)1057 })1058 })1059 })10601061 // Reported by: https://github.com/mweststrate/immer/issues/3431062 it("ensures each property is drafted", () => {1063 produce({a: {}, b: {}}, parent => {1064 parent.a // Access "a" but not "b"1065 produce(parent, child => {1066 child.c = 11067 expect(isDraft(child.a)).toBeTruthy()1068 expect(isDraft(child.b)).toBeTruthy()1069 })1070 })1071 })10721073 it("preserves any pending changes", () => {1074 produce({a: 1, b: 1, d: 1}, parent => {1075 parent.b = 21076 parent.c = 21077 delete parent.d1078 produce(parent, child => {1079 expect(child.a).toBe(1) // unchanged1080 expect(child.b).toBe(2) // changed1081 expect(child.c).toBe(2) // added1082 expect(child.d).toBeUndefined() // deleted1083 })1084 })1085 })1086 })10871088 describe("when base state contains a draft", () => {1089 it("wraps unowned draft with its own draft", () => {1090 produce({a: {}}, parent => {1091 produce({a: parent.a}, child => {1092 expect(child.a).not.toBe(parent.a)1093 expect(isDraft(child.a)).toBeTruthy()1094 expect(original(child.a)).toBe(parent.a)1095 })1096 })1097 })10981099 it("returns unowned draft if no changes were made", () => {1100 produce({a: {}}, parent => {1101 const result = produce({a: parent.a}, () => {})1102 expect(result.a).toBe(parent.a)1103 })1104 })11051106 it("clones the unowned draft when changes are made", () => {1107 produce({a: {}}, parent => {1108 const result = produce({a: parent.a}, child => {1109 child.a.b = 11110 })1111 expect(result.a).not.toBe(parent.a)1112 expect(result.a.b).toBe(1)1113 expect("b" in parent.a).toBeFalsy()1114 })1115 })11161117 // We cannot auto-freeze the result of a nested producer,1118 // because it may contain a draft from a parent producer.1119 it("never auto-freezes the result", () => {1120 produce({a: {}}, parent => {1121 const r = produce({a: parent.a}, child => {1122 child.b = 1 // Ensure a copy is returned.1123 })1124 expect(Object.isFrozen(r)).toBeFalsy()1125 })1126 })1127 })11281129 // "Upvalues" are variables from a parent scope.1130 it("does not finalize upvalue drafts", () => {1131 produce({a: {}, b: {}}, parent => {1132 expect(produce({}, () => parent)).toBe(parent)1133 parent.x // Ensure proxy not revoked.11341135 expect(produce({}, () => [parent])[0]).toBe(parent)1136 parent.x // Ensure proxy not revoked.11371138 expect(produce({}, () => parent.a)).toBe(parent.a)1139 parent.a.x // Ensure proxy not revoked.11401141 // Modified parent test1142 parent.c = 11143 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1144 parent.b.x // Ensure proxy not revoked.1145 })1146 })11471148 it("works with interweaved Immer instances", () => {1149 const options = {useProxies, autoFreeze}1150 const one = createPatchedImmer(options)1151 const two = createPatchedImmer(options)11521153 const base = {}1154 const result = one.produce(base, s1 =>1155 two.produce({s1}, s2 => {1156 expect(original(s2.s1)).toBe(s1)1157 s2.n = 11158 s2.s1 = one.produce({s2}, s3 => {1159 expect(original(s3.s2)).toBe(s2)1160 expect(original(s3.s2.s1)).toBe(s2.s1)1161 return s3.s2.s11162 })1163 })1164 )1165 expect(result.n).toBe(1)1166 expect(result.s1).toBe(base)1167 })1168 })11691170 if (useProxies)1171 it("throws when Object.setPrototypeOf() is used on a draft", () => {1172 produce({}, draft => {1173 expect(() =>1174 Object.setPrototypeOf(draft, Array)1175 ).toThrowErrorMatchingSnapshot()1176 })1177 })11781179 it("supports the 'in' operator", () => {1180 produce(baseState, draft => {1181 // Known property1182 expect("anArray" in draft).toBe(true)1183 expect(Reflect.has(draft, "anArray")).toBe(true)11841185 // Unknown property1186 expect("bla" in draft).toBe(false)1187 expect(Reflect.has(draft, "bla")).toBe(false)11881189 // Known index1190 expect(0 in draft.anArray).toBe(true)1191 expect("0" in draft.anArray).toBe(true)1192 expect(Reflect.has(draft.anArray, 0)).toBe(true)1193 expect(Reflect.has(draft.anArray, "0")).toBe(true)11941195 // Unknown index1196 expect(17 in draft.anArray).toBe(false)1197 expect("17" in draft.anArray).toBe(false)1198 expect(Reflect.has(draft.anArray, 17)).toBe(false)1199 expect(Reflect.has(draft.anArray, "17")).toBe(false)1200 })1201 })12021203 it("'this' should not be bound anymore - 1", () => {1204 const base = {x: 3}1205 const next1 = produce(base, function() {1206 expect(this).toBe(undefined)1207 })1208 })12091210 it("'this' should not be bound anymore - 2", () => {1211 const incrementor = produce(function() {1212 expect(this).toBe(undefined)1213 })1214 incrementor()1215 })12161217 it("should be possible to use dynamic bound this", () => {1218 const world = {1219 counter: {count: 1},1220 inc: produce(function(draft) {1221 expect(this).toBe(world)1222 draft.counter.count = this.counter.count + 11223 })1224 }12251226 expect(world.inc(world).counter.count).toBe(2)1227 })12281229 // See here: https://github.com/mweststrate/immer/issues/891230 it("supports the spread operator", () => {1231 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1232 const result = produce(base, draft => {1233 draft.foo = {x: 1, ...draft.foo, y: 1}1234 draft.bar = [1, ...draft.bar, 1]1235 })1236 expect(result).toEqual({1237 foo: {x: 0, y: 1},1238 bar: [1, 0, 0, 1]1239 })1240 })12411242 it("processes with lodash.set", () => {1243 const base = [{id: 1, a: 1}]1244 const result = produce(base, draft => {1245 lodash.set(draft, "[0].a", 2)1246 })1247 expect(base[0].a).toEqual(1)1248 expect(result[0].a).toEqual(2)1249 })12501251 it("processes with lodash.find", () => {1252 const base = [{id: 1, a: 1}]1253 const result = produce(base, draft => {1254 const obj1 = lodash.find(draft, {id: 1})1255 lodash.set(obj1, "a", 2)1256 })1257 expect(base[0].a).toEqual(1)1258 expect(result[0].a).toEqual(2)1259 })12601261 autoFreeze &&1262 test("issue #469, state not frozen", () => {1263 const project = produce(1264 {1265 id: 1,1266 tracks: [{id: 1}]1267 },1268 () => {}1269 )12701271 expect(() => {1272 project.id = 2 // Does not throw error1273 }).toThrowError("Cannot assign to read only property 'id'")12741275 expect(() => {1276 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1277 }).toThrowError("Cannot assign to read only property 'id'")1278 })12791280 describe("recipe functions", () => {1281 it("can return a new object", () => {1282 const base = {x: 3}1283 const res = produce(base, d => {1284 return {x: d.x + 1}1285 })1286 expect(res).not.toBe(base)1287 expect(res).toEqual({x: 4})1288 })12891290 it("can return the draft", () => {1291 const base = {x: 3}1292 const res = produce(base, d => {1293 d.x = 41294 return d1295 })1296 expect(res).not.toBe(base)1297 expect(res).toEqual({x: 4})1298 })12991300 it("can return an unmodified child draft", () => {1301 const base = {a: {}}1302 const res = produce(base, d => {1303 return d.a1304 })1305 expect(res).toBe(base.a)1306 })13071308 // TODO: Avoid throwing if only the child draft was modified.1309 it("cannot return a modified child draft", () => {1310 const base = {a: {}}1311 expect(() => {1312 produce(base, d => {1313 d.a.b = 11314 return d.a1315 })1316 }).toThrowErrorMatchingSnapshot()1317 })13181319 it("can return a frozen object", () => {1320 const res = deepFreeze([{x: 3}])1321 expect(produce({}, () => res)).toBe(res)1322 })13231324 it("can return an object with two references to another object", () => {1325 const next = produce({}, d => {1326 const obj = {}1327 return {obj, arr: [obj]}1328 })1329 expect(next.obj).toBe(next.arr[0])1330 })13311332 it("can return an object with two references to an unmodified draft", () => {1333 const base = {a: {}}1334 const next = produce(base, d => {1335 return [d.a, d.a]1336 })1337 expect(next[0]).toBe(base.a)1338 expect(next[0]).toBe(next[1])1339 })13401341 it("cannot return an object that references itself", () => {1342 const res = {}1343 res.self = res1344 expect(() => {1345 produce(res, () => res.self)1346 }).toThrowErrorMatchingSnapshot()1347 })1348 })13491350 describe("async recipe function", () => {1351 it("can modify the draft", () => {1352 const base = {a: 0, b: 0}1353 return produce(base, async d => {1354 d.a = 11355 await Promise.resolve()1356 d.b = 11357 }).then(res => {1358 expect(res).not.toBe(base)1359 expect(res).toEqual({a: 1, b: 1})1360 })1361 })13621363 it("works with rejected promises", () => {1364 let draft1365 const base = {a: 0, b: 0}1366 const err = new Error("passed")1367 return produce(base, d => {1368 draft = d1369 draft.b = 11370 return Promise.reject(err)1371 }).then(1372 () => {1373 throw "failed"1374 },1375 e => {1376 expect(e).toBe(err)1377 expect(() => draft.a).toThrowErrorMatchingSnapshot()1378 }1379 )1380 })13811382 it("supports recursive produce calls after await", () => {1383 const base = {obj: {k: 1}}1384 return produce(base, d => {1385 const obj = d.obj1386 delete d.obj1387 return Promise.resolve().then(() => {1388 d.a = produce({}, d => {1389 d.b = obj // Assign a draft owned by the parent scope.1390 })13911392 // Auto-freezing is prevented when an unowned draft exists.1393 expect(Object.isFrozen(d.a)).toBeFalsy()13941395 // Ensure `obj` is not revoked.1396 obj.c = 11397 })1398 }).then(res => {1399 expect(res).not.toBe(base)1400 expect(res).toEqual({1401 a: {b: {k: 1, c: 1}}1402 })1403 })1404 })1405 })14061407 it("throws when the draft is modified and another object is returned", () => {1408 const base = {x: 3}1409 expect(() => {1410 produce(base, draft => {1411 draft.x = 41412 return {x: 5}1413 })1414 }).toThrowErrorMatchingSnapshot()1415 })14161417 it("should fix #117 - 1", () => {1418 const reducer = (state, action) =>1419 produce(state, draft => {1420 switch (action.type) {1421 case "SET_STARTING_DOTS":1422 return draft.availableStartingDots.map(a => a)1423 default:1424 break1425 }1426 })1427 const base = {1428 availableStartingDots: [1429 {dots: 4, count: 1},1430 {dots: 3, count: 2},1431 {dots: 2, count: 3},1432 {dots: 1, count: 4}1433 ]1434 }1435 const next = reducer(base, {type: "SET_STARTING_DOTS"})1436 expect(next).toEqual(base.availableStartingDots)1437 expect(next).not.toBe(base.availableStartingDots)1438 })14391440 it("should fix #117 - 2", () => {1441 const reducer = (state, action) =>1442 produce(state, draft => {1443 switch (action.type) {1444 case "SET_STARTING_DOTS":1445 return {1446 dots: draft.availableStartingDots.map(a => a)1447 }1448 default:1449 break1450 }1451 })1452 const base = {1453 availableStartingDots: [1454 {dots: 4, count: 1},1455 {dots: 3, count: 2},1456 {dots: 2, count: 3},1457 {dots: 1, count: 4}1458 ]1459 }1460 const next = reducer(base, {type: "SET_STARTING_DOTS"})1461 expect(next).toEqual({dots: base.availableStartingDots})1462 })14631464 it("cannot always detect noop assignments - 0", () => {1465 const baseState = {x: {y: 3}}1466 const nextState = produce(baseState, d => {1467 const a = d.x1468 d.x = a1469 })1470 expect(nextState).toBe(baseState)1471 })14721473 it("cannot always detect noop assignments - 1", () => {1474 const baseState = {x: {y: 3}}1475 const nextState = produce(baseState, d => {1476 const a = d.x1477 d.x = 41478 d.x = a1479 })1480 // Ideally, this should actually be the same instances1481 // but this would be pretty expensive to detect,1482 // so we don't atm1483 expect(nextState).not.toBe(baseState)1484 })14851486 it("cannot always detect noop assignments - 2", () => {1487 const baseState = {x: {y: 3}}1488 const nextState = produce(baseState, d => {1489 const a = d.x1490 const stuff = a.y + 31491 d.x = 41492 d.x = a1493 })1494 // Ideally, this should actually be the same instances1495 // but this would be pretty expensive to detect,1496 // so we don't atm1497 expect(nextState).not.toBe(baseState)1498 })14991500 it("cannot always detect noop assignments - 3", () => {1501 const baseState = {x: 3}1502 const nextState = produce(baseState, d => {1503 d.x = 31504 })1505 expect(nextState).toBe(baseState)1506 })15071508 it("cannot always detect noop assignments - 4", () => {1509 const baseState = {x: 3}1510 const nextState = produce(baseState, d => {1511 d.x = 41512 d.x = 31513 })1514 // Ideally, this should actually be the same instances1515 // but this would be pretty expensive to detect,1516 // so we don't atm1517 expect(nextState).not.toBe(baseState)1518 })15191520 it("cannot produce undefined by returning undefined", () => {1521 const base = 31522 expect(produce(base, () => 4)).toBe(4)1523 expect(produce(base, () => null)).toBe(null)1524 expect(produce(base, () => undefined)).toBe(3)1525 expect(produce(base, () => {})).toBe(3)1526 expect(produce(base, () => nothing)).toBe(undefined)15271528 expect(produce({}, () => undefined)).toEqual({})1529 expect(produce({}, () => nothing)).toBe(undefined)1530 expect(produce(3, () => nothing)).toBe(undefined)15311532 expect(produce(() => undefined)({})).toEqual({})1533 expect(produce(() => nothing)({})).toBe(undefined)1534 expect(produce(() => nothing)(3)).toBe(undefined)1535 })15361537 describe("base state type", () => {1538 testObjectTypes(produce)1539 testLiteralTypes(produce)1540 })15411542 afterEach(() => {1543 expect(baseState).toBe(origBaseState)1544 expect(baseState).toEqual(createBaseState())1545 })15461547 class Foo {}1548 function createBaseState() {1549 const data = {1550 anInstance: new Foo(),1551 anArray: [3, 2, {c: 3}, 1],1552 aMap: new Map([1553 ["jedi", {name: "Luke", skill: 10}],1554 ["jediTotal", 42],1555 ["force", "these aren't the droids you're looking for"]1556 ]),1557 aSet: new Set([1558 "Luke",1559 42,1560 {1561 jedi: "Yoda"1562 }1563 ]),1564 aProp: "hi",1565 anObject: {1566 nested: {1567 yummie: true1568 },1569 coffee: false1570 }1571 }1572 return autoFreeze ? deepFreeze(data) : data1573 }1574 })15751576 describe(`isDraft - ${name}`, () => {1577 it("returns true for object drafts", () => {1578 produce({}, state => {1579 expect(isDraft(state)).toBeTruthy()1580 })1581 })1582 it("returns true for array drafts", () => {1583 produce([], state => {1584 expect(isDraft(state)).toBeTruthy()1585 })1586 })1587 it("returns true for objects nested in object drafts", () => {1588 produce({a: {b: {}}}, state => {1589 expect(isDraft(state.a)).toBeTruthy()1590 expect(isDraft(state.a.b)).toBeTruthy()1591 })1592 })1593 it("returns false for new objects added to a draft", () => {1594 produce({}, state => {1595 state.a = {}1596 expect(isDraft(state.a)).toBeFalsy()1597 })1598 })1599 it("returns false for objects returned by the producer", () => {1600 const object = produce(null, Object.create)1601 expect(isDraft(object)).toBeFalsy()1602 })1603 it("returns false for arrays returned by the producer", () => {1604 const array = produce(null, _ => [])1605 expect(isDraft(array)).toBeFalsy()1606 })1607 it("returns false for object drafts returned by the producer", () => {1608 const object = produce({}, state => state)1609 expect(isDraft(object)).toBeFalsy()1610 })1611 it("returns false for array drafts returned by the producer", () => {1612 const array = produce([], state => state)1613 expect(isDraft(array)).toBeFalsy()1614 })1615 })16161617 describe(`complex nesting map / set / object`, () => {1618 const a = {a: 1}1619 const b = {b: 2}1620 const c = {c: 3}1621 const set1 = new Set([a, b])1622 const set2 = new Set([c])1623 const map = new Map([["set1", set1], ["set2", set2]])1624 const base = {map}16251626 function first(set) {1627 return Array.from(set.values())[0]1628 }16291630 function second(set) {1631 return Array.from(set.values())[1]1632 }16331634 test(`modify deep object`, () => {1635 const [res, patches] = produceWithPatches(base, draft => {1636 const v = first(draft.map.get("set1"))1637 expect(original(v)).toBe(a)1638 expect(v).toEqual(a)1639 expect(v).not.toBe(a)1640 v.a++1641 })1642 expect(res).toMatchSnapshot()1643 expect(patches).toMatchSnapshot()1644 expect(a.a).toBe(1)1645 expect(base.map.get("set1")).toBe(set1)1646 expect(first(base.map.get("set1"))).toBe(a)1647 expect(res).not.toBe(base)1648 expect(res.map).not.toBe(base.map)1649 expect(res.map.get("set1")).not.toBe(base.map.get("set1"))1650 expect(second(base.map.get("set1"))).toBe(b)1651 expect(base.map.get("set2")).toBe(set2)1652 expect(first(res.map.get("set1"))).toEqual({a: 2})1653 })16541655 test(`modify deep object - keep value`, () => {1656 const [res, patches] = produceWithPatches(base, draft => {1657 const v = first(draft.map.get("set1"))1658 expect(original(v)).toBe(a)1659 expect(v).toEqual(a)1660 expect(v).not.toBe(a)1661 v.a = 1 // same value1662 })1663 expect(a.a).toBe(1)1664 expect(base.map.get("set1")).toBe(set1)1665 expect(first(base.map.get("set1"))).toBe(a)1666 expect(res).toBe(base)1667 expect(res.map).toBe(base.map)1668 expect(res.map.get("set1")).toBe(base.map.get("set1"))1669 expect(first(res.map.get("set1"))).toBe(a)1670 expect(second(base.map.get("set1"))).toBe(b)1671 expect(base.map.get("set2")).toBe(set2)1672 expect(patches.length).toBe(0)1673 })1674 })1675}16761677function testObjectTypes(produce) {1678 class Foo {1679 constructor(foo) {1680 this.foo = foo1681 this[immerable] = true1682 }1683 }1684 const values = {1685 "empty object": {},1686 "plain object": {a: 1, b: 2},1687 "object (no prototype)": Object.create(null),1688 "empty array": [],1689 "plain array": [1, 2],1690 "class instance (draftable)": new Foo(1)1691 }1692 for (const name in values) {1693 const value = values[name]1694 const copy = shallowCopy(value)1695 testObjectType(name, value)1696 testObjectType(name + " (frozen)", Object.freeze(copy))1697 }1698 function testObjectType(name, base) {1699 describe(name, () => {1700 it("creates a draft", () => {1701 produce(base, draft => {1702 expect(draft).not.toBe(base)1703 expect(shallowCopy(draft, true)).toEqual(base)1704 })1705 })17061707 it("preserves the prototype", () => {1708 const proto = Object.getPrototypeOf(base)1709 produce(base, draft => {1710 expect(Object.getPrototypeOf(draft)).toBe(proto)1711 })1712 })17131714 it("returns the base state when no changes are made", () => {1715 expect(produce(base, () => {})).toBe(base)1716 })17171718 it("returns a copy when changes are made", () => {1719 const random = Math.random()1720 const result = produce(base, draft => {1721 draft[0] = random1722 })1723 expect(result).not.toBe(base)1724 expect(result.constructor).toBe(base.constructor)1725 expect(result[0]).toBe(random)1726 })1727 })1728 }1729}17301731function testLiteralTypes(produce) {1732 class Foo {}1733 const values = {1734 "falsy number": 0,1735 "truthy number": 1,1736 "negative number": -1,1737 NaN: NaN,1738 infinity: 1 / 0,1739 true: true,1740 false: false,1741 "empty string": "",1742 "truthy string": "1",1743 null: null,1744 undefined: undefined,17451746 /**1747 * These objects are treated as literals because Immer1748 * does not know how to draft them.1749 */1750 function: () => {},1751 "regexp object": /.+/g,1752 "boxed number": new Number(0),1753 "boxed string": new String(""),1754 "boxed boolean": new Boolean(),1755 "date object": new Date(),1756 "class instance (not draftable)": new Foo()1757 }1758 for (const name in values) {1759 describe(name, () => {1760 const value = values[name]17611762 it("does not create a draft", () => {1763 produce(value, draft => {1764 expect(draft).toBe(value)1765 })1766 })17671768 it("returns the base state when no changes are made", () => {1769 expect(produce(value, () => {})).toBe(value)1770 })17711772 if (value && typeof value == "object") {1773 it("does not return a copy when changes are made", () => {1774 expect(1775 produce(value, draft => {1776 draft.foo = true1777 })1778 ).toBe(value)1779 })1780 }1781 })1782 }1783}17841785function enumerableOnly(x) {1786 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1787 each(copy, (prop, value) => {1788 if (value && typeof value === "object") {1789 copy[prop] = enumerableOnly(value)1790 }1791 })1792 return copy1793}