base.js
This file
Path
__tests__/base.js
2,452 lines · 61.5 KiB · JavaScript
Last changed by
fix: Fixed #620: Symbolic properties were not drafted or finalized correctlyMichel Weststratebefore adoption91915cf
History of this fileTake it
1"use strict"2import {3 Immer,4 nothing,5 original,6 isDraft,7 immerable,8 enableAllPlugins9} from "../src/immer"10import {each, shallowCopy, DRAFT_STATE} from "../src/internal"11import deepFreeze from "deep-freeze"12import cloneDeep from "lodash.clonedeep"13import * as lodash from "lodash"1415jest.setTimeout(1000)1617enableAllPlugins()1819test("immer should have no dependencies", () => {20 expect(require("../package.json").dependencies).toBeUndefined()21})2223runBaseTest("proxy (no freeze)", true, false)24runBaseTest("proxy (autofreeze)", true, true)25runBaseTest("proxy (patch listener)", true, false, true)26runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)2728runBaseTest("es5 (no freeze)", false, false)29runBaseTest("es5 (autofreeze)", false, true)30runBaseTest("es5 (patch listener)", false, false, true)31runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)3233function runBaseTest(name, useProxies, autoFreeze, useListener) {34 const listener = useListener ? function() {} : undefined35 const {produce, produceWithPatches} = createPatchedImmer({36 useProxies,37 autoFreeze38 })3940 // When `useListener` is true, append a function to the arguments of every41 // uncurried `produce` call in every test. This makes tests easier to read.42 function createPatchedImmer(options) {43 const immer = new Immer(options)4445 const {produce} = immer46 immer.produce = function(...args) {47 return typeof args[1] === "function" && args.length < 348 ? produce(...args, listener)49 : produce(...args)50 }5152 return immer53 }5455 describe(`base functionality - ${name}`, () => {56 let baseState57 let origBaseState5859 beforeEach(() => {60 origBaseState = baseState = createBaseState()61 })6263 it("returns the original state when no changes are made", () => {64 const nextState = produce(baseState, s => {65 expect(s.aProp).toBe("hi")66 expect(s.anObject.nested).toMatchObject({yummie: true})67 })68 expect(nextState).toBe(baseState)69 })7071 it("does structural sharing", () => {72 const random = Math.random()73 const nextState = produce(baseState, s => {74 s.aProp = random75 })76 expect(nextState).not.toBe(baseState)77 expect(nextState.aProp).toBe(random)78 expect(nextState.nested).toBe(baseState.nested)79 })8081 it("deep change bubbles up", () => {82 const nextState = produce(baseState, s => {83 s.anObject.nested.yummie = false84 })85 expect(nextState).not.toBe(baseState)86 expect(nextState.anObject).not.toBe(baseState.anObject)87 expect(baseState.anObject.nested.yummie).toBe(true)88 expect(nextState.anObject.nested.yummie).toBe(false)89 expect(nextState.anArray).toBe(baseState.anArray)90 })9192 it("can add props", () => {93 const nextState = produce(baseState, s => {94 s.anObject.cookie = {tasty: true}95 })96 expect(nextState).not.toBe(baseState)97 expect(nextState.anObject).not.toBe(baseState.anObject)98 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)99 expect(nextState.anObject.cookie).toEqual({tasty: true})100 })101102 it("can delete props", () => {103 const nextState = produce(baseState, s => {104 delete s.anObject.nested105 })106 expect(nextState).not.toBe(baseState)107 expect(nextState.anObject).not.toBe(baseState.anObject)108 expect(nextState.anObject.nested).toBe(undefined)109 })110111 // Found by: https://github.com/mweststrate/immer/pull/267112 it("can delete props added in the producer", () => {113 const nextState = produce(baseState, s => {114 s.anObject.test = true115 delete s.anObject.test116 })117 if (useProxies) {118 expect(nextState).not.toBe(baseState)119 expect(nextState).toEqual(baseState)120 } else {121 // The copy is avoided in ES5.122 expect(nextState).toBe(baseState)123 }124 })125126 // Found by: https://github.com/mweststrate/immer/issues/328127 it("can set a property that was just deleted", () => {128 const baseState = {a: 1}129 const nextState = produce(baseState, s => {130 delete s.a131 s.a = 2132 })133 expect(nextState.a).toBe(2)134 })135136 it("can set a property to its original value after deleting it", () => {137 const baseState = {a: {b: 1}}138 const nextState = produce(baseState, s => {139 const a = s.a140 delete s.a141 s.a = a142 })143 if (useProxies) {144 expect(nextState).not.toBe(baseState)145 expect(nextState).toEqual(baseState)146 } else {147 // The copy is avoided in ES5.148 expect(nextState).toBe(baseState)149 }150 })151152 it("can get property descriptors", () => {153 const getDescriptor = Object.getOwnPropertyDescriptor154 const baseState = deepFreeze([{a: 1}])155 produce(baseState, arr => {156 const obj = arr[0]157 const desc = {158 configurable: true,159 enumerable: true,160 ...(useProxies && {writable: true})161 }162163 // Known property164 expect(getDescriptor(obj, "a")).toMatchObject(desc)165 expect(getDescriptor(arr, 0)).toMatchObject(desc)166167 // Deleted property168 delete obj.a169 arr.pop()170 expect(getDescriptor(obj, "a")).toBeUndefined()171 expect(getDescriptor(arr, 0)).toBeUndefined()172173 // Unknown property174 expect(getDescriptor(obj, "b")).toBeUndefined()175 expect(getDescriptor(arr, 100)).toBeUndefined()176177 // Added property178 obj.b = 2179 arr[100] = 1180 expect(getDescriptor(obj, "b")).toBeDefined()181 expect(getDescriptor(arr, 100)).toBeDefined()182 })183 })184185 describe("array drafts", () => {186 it("supports Array.isArray()", () => {187 const nextState = produce(baseState, s => {188 expect(Array.isArray(s.anArray)).toBeTruthy()189 s.anArray.push(1)190 })191 expect(Array.isArray(nextState.anArray)).toBeTruthy()192 })193194 it("supports index access", () => {195 const value = baseState.anArray[0]196 const nextState = produce(baseState, s => {197 expect(s.anArray[0]).toBe(value)198 })199 expect(nextState).toBe(baseState)200 })201202 it("supports iteration", () => {203 const base = [204 {id: 1, a: 1},205 {id: 2, a: 1}206 ]207 const findById = (collection, id) => {208 for (const item of collection) {209 if (item.id === id) return item210 }211 return null212 }213 const result = produce(base, draft => {214 const obj1 = findById(draft, 1)215 const obj2 = findById(draft, 2)216 obj1.a = 2217 obj2.a = 2218 })219 expect(result[0].a).toEqual(2)220 expect(result[1].a).toEqual(2)221 })222223 it("can assign an index via bracket notation", () => {224 const nextState = produce(baseState, s => {225 s.anArray[3] = true226 })227 expect(nextState).not.toBe(baseState)228 expect(nextState.anArray).not.toBe(baseState.anArray)229 expect(nextState.anArray[3]).toEqual(true)230 })231232 it("can use splice() to both add and remove items", () => {233 const nextState = produce(baseState, s => {234 s.anArray.splice(1, 1, "a", "b")235 })236 expect(nextState.anArray).not.toBe(baseState.anArray)237 expect(nextState.anArray[1]).toBe("a")238 expect(nextState.anArray[2]).toBe("b")239 })240241 it("can truncate via the length property", () => {242 const baseLength = baseState.anArray.length243 const nextState = produce(baseState, s => {244 s.anArray.length = baseLength - 1245 })246 expect(nextState.anArray).not.toBe(baseState.anArray)247 expect(nextState.anArray.length).toBe(baseLength - 1)248 })249250 it("can extend via the length property", () => {251 const baseLength = baseState.anArray.length252 const nextState = produce(baseState, s => {253 s.anArray.length = baseLength + 1254 })255 expect(nextState.anArray).not.toBe(baseState.anArray)256 expect(nextState.anArray.length).toBe(baseLength + 1)257 })258259 // Reported here: https://github.com/mweststrate/immer/issues/116260 it("can pop then push", () => {261 const nextState = produce([1, 2, 3], s => {262 s.pop()263 s.push(100)264 })265 expect(nextState).toEqual([1, 2, 100])266 })267268 it("can be sorted", () => {269 const baseState = [3, 1, 2]270 const nextState = produce(baseState, s => {271 s.sort()272 })273 expect(nextState).not.toBe(baseState)274 expect(nextState).toEqual([1, 2, 3])275 })276277 it("supports modifying nested objects", () => {278 const baseState = [{a: 1}, {}]279 const nextState = produce(baseState, s => {280 s[0].a++281 s[1].a = 0282 })283 expect(nextState).not.toBe(baseState)284 expect(nextState[0].a).toBe(2)285 expect(nextState[1].a).toBe(0)286 })287288 it("never preserves non-numeric properties", () => {289 const baseState = []290 baseState.x = 7291 const nextState = produce(baseState, s => {292 s.push(3)293 })294 expect("x" in nextState).toBeFalsy()295 })296297 if (useProxies && !global.USES_BUILD) {298 it("throws when a non-numeric property is added", () => {299 expect(() => {300 produce([], d => {301 d.x = 3302 })303 }).toThrowErrorMatchingSnapshot()304 })305306 it("throws when a non-numeric property is deleted", () => {307 expect(() => {308 const baseState = []309 baseState.x = 7310 produce(baseState, d => {311 delete d.x312 })313 }).toThrowErrorMatchingSnapshot()314 })315 }316 })317318 describe("map drafts", () => {319 it("supports key access", () => {320 const value = baseState.aMap.get("jedi")321 const nextState = produce(baseState, s => {322 expect(s.aMap.get("jedi")).toEqual(value)323 })324 expect(nextState).toBe(baseState)325 })326327 it("supports key access for non-primitive keys", () => {328 const key = {prop: "val"}329 const base = new Map([[key, {id: 1, a: 1}]])330 const value = base.get(key)331 const nextState = produce(base, s => {332 expect(s.get(key)).toEqual(value)333 })334 expect(nextState).toBe(base)335 })336337 it("supports iteration", () => {338 const base = new Map([339 ["first", {id: 1, a: 1}],340 ["second", {id: 2, a: 1}]341 ])342 const findById = (map, id) => {343 for (const [, item] of map) {344 if (item.id === id) return item345 }346 return null347 }348 const result = produce(base, draft => {349 const obj1 = findById(draft, 1)350 const obj2 = findById(draft, 2)351 obj1.a = 2352 obj2.a = 2353 })354 expect(result).not.toBe(base)355 expect(result.get("first").a).toEqual(2)356 expect(result.get("second").a).toEqual(2)357 })358359 it("supports 'entries'", () => {360 const base = new Map([361 ["first", {id: 1, a: 1}],362 ["second", {id: 2, a: 1}]363 ])364 const findById = (map, id) => {365 for (const [, item] of map.entries()) {366 if (item.id === id) return item367 }368 return null369 }370 const result = produce(base, draft => {371 const obj1 = findById(draft, 1)372 const obj2 = findById(draft, 2)373 obj1.a = 2374 obj2.a = 2375 })376 expect(result).not.toBe(base)377 expect(result.get("first").a).toEqual(2)378 expect(result.get("second").a).toEqual(2)379 })380381 it("supports 'values'", () => {382 const base = new Map([383 ["first", {id: 1, a: 1}],384 ["second", {id: 2, a: 1}]385 ])386 const findById = (map, id) => {387 for (const item of map.values()) {388 if (item.id === id) return item389 }390 return null391 }392 const result = produce(base, draft => {393 const obj1 = findById(draft, 1)394 const obj2 = findById(draft, 2)395 obj1.a = 2396 obj2.a = 2397 })398 expect(result).not.toBe(base)399 expect(result.get("first").a).toEqual(2)400 expect(result.get("second").a).toEqual(2)401 })402403 it("supports 'keys", () => {404 const base = new Map([405 ["first", Symbol()],406 ["second", Symbol()]407 ])408 const result = produce(base, draft => {409 expect([...draft.keys()]).toEqual(["first", "second"])410 draft.set("third", Symbol())411 expect([...draft.keys()]).toEqual(["first", "second", "third"])412 })413 })414415 it("supports forEach", () => {416 const key1 = {prop: "val1"}417 const key2 = {prop: "val2"}418 const base = new Map([419 ["first", {id: 1, a: 1}],420 ["second", {id: 2, a: 1}],421 [key1, {id: 3, a: 1}],422 [key2, {id: 4, a: 1}]423 ])424 const result = produce(base, draft => {425 let sum1 = 0426 draft.forEach(({a}) => {427 sum1 += a428 })429 expect(sum1).toBe(4)430 let sum2 = 0431 draft.get("first").a = 10432 draft.get("second").a = 20433 draft.get(key1).a = 30434 draft.get(key2).a = 40435 draft.forEach(({a}) => {436 sum2 += a437 })438 expect(sum2).toBe(100)439 })440 expect(result).not.toBe(base)441 expect(base.get("first").a).toEqual(1)442 expect(base.get("second").a).toEqual(1)443 expect(base.get(key1).a).toEqual(1)444 expect(base.get(key2).a).toEqual(1)445 expect(result.get("first").a).toEqual(10)446 expect(result.get("second").a).toEqual(20)447 expect(result.get(key1).a).toEqual(30)448 expect(result.get(key2).a).toEqual(40)449 })450451 it("supports forEach mutation", () => {452 const base = new Map([453 ["first", {id: 1, a: 1}],454 ["second", {id: 2, a: 1}]455 ])456 const result = produce(base, draft => {457 draft.forEach(item => {458 item.a = 100459 })460 })461 expect(result).not.toBe(base)462 expect(result.get("first").a).toEqual(100)463 expect(result.get("second").a).toEqual(100)464 })465466 it("can assign by key", () => {467 const nextState = produce(baseState, s => {468 // Map.prototype.set should return the Map itself469 const res = s.aMap.set("force", true)470 if (!global.USES_BUILD) expect(res).toBe(s.aMap[DRAFT_STATE].draft_)471 })472 expect(nextState).not.toBe(baseState)473 expect(nextState.aMap).not.toBe(baseState.aMap)474 expect(nextState.aMap.get("force")).toEqual(true)475 })476477 it("can assign by a non-primitive key", () => {478 const key = {prop: "val"}479 const value = {id: 1, a: 1}480 const base = new Map([[key, value]])481 const nextState = produce(base, s => {482 s.set(key, true)483 })484 expect(nextState).not.toBe(base)485 expect(base.get(key)).toEqual(value)486 expect(nextState.get(key)).toEqual(true)487 })488489 it("state stays the same if the the same item is assigned by key", () => {490 const nextState = produce(baseState, s => {491 s.aMap.set("jediTotal", 42)492 })493 expect(nextState).toBe(baseState)494 expect(nextState.aMap).toBe(baseState.aMap)495 })496497 it("returns 'size'", () => {498 const nextState = produce(baseState, s => {499 s.aMap.set("newKey", true)500 expect(s.aMap.size).toBe(baseState.aMap.size + 1)501 })502 expect(nextState).not.toBe(baseState)503 expect(nextState.aMap).not.toBe(baseState.aMap)504 expect(nextState.aMap.get("newKey")).toEqual(true)505 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)506 })507508 it("can use 'delete' to remove items", () => {509 const nextState = produce(baseState, s => {510 expect(s.aMap.has("jedi")).toBe(true)511 expect(s.aMap.delete("jedi")).toBe(true)512 expect(s.aMap.has("jedi")).toBe(false)513 })514 expect(nextState.aMap).not.toBe(baseState.aMap)515 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)516 expect(baseState.aMap.has("jedi")).toBe(true)517 expect(nextState.aMap.has("jedi")).toBe(false)518 })519520 it("can use 'clear' to remove items", () => {521 const nextState = produce(baseState, s => {522 expect(s.aMap.size).not.toBe(0)523 s.aMap.clear()524 expect(s.aMap.size).toBe(0)525 })526 expect(nextState.aMap).not.toBe(baseState.aMap)527 expect(baseState.aMap.size).not.toBe(0)528 expect(nextState.aMap.size).toBe(0)529 })530531 it("support 'has'", () => {532 const nextState = produce(baseState, s => {533 expect(s.aMap.has("newKey")).toBe(false)534 s.aMap.set("newKey", true)535 expect(s.aMap.has("newKey")).toBe(true)536 })537 expect(nextState).not.toBe(baseState)538 expect(nextState.aMap).not.toBe(baseState.aMap)539 expect(baseState.aMap.has("newKey")).toBe(false)540 expect(nextState.aMap.has("newKey")).toBe(true)541 })542543 it("supports nested maps", () => {544 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])545 const result = produce(base, draft => {546 draft.get("first").get("second").prop = "test1"547 })548 expect(result).not.toBe(base)549 expect(result.get("first")).not.toBe(base.get("first"))550 expect(result.get("first").get("second")).not.toBe(551 base.get("first").get("second")552 )553 expect(base.get("first").get("second").prop).toBe("test")554 expect(result.get("first").get("second").prop).toBe("test1")555 })556557 it("treats void deletes as no-op", () => {558 const base = new Map([["x", 1]])559 const next = produce(base, d => {560 expect(d.delete("y")).toBe(false)561 })562 expect(next).toBe(base)563 })564565 it("revokes map proxies", () => {566 let m567 produce(baseState, s => {568 m = s.aMap569 })570 expect(() => m.get("x")).toThrowErrorMatchingSnapshot()571 expect(() => m.set("x", 3)).toThrowErrorMatchingSnapshot()572 })573574 it("does not draft map keys", () => {575 // anything else would be terribly confusing576 const key = {a: 1}577 const map = new Map([[key, 2]])578 const next = produce(map, d => {579 const dKey = Array.from(d.keys())[0]580 expect(isDraft(dKey)).toBe(false)581 expect(dKey).toBe(key)582 dKey.a += 1583 d.set(dKey, d.get(dKey) + 1)584 d.set(key, d.get(key) + 1)585 expect(d.get(key)).toBe(4)586 expect(key.a).toBe(2)587 })588 const entries = Array.from(next.entries())589 expect(entries).toEqual([[key, 4]])590 expect(entries[0][0]).toBe(key)591 expect(entries[0][0].a).toBe(2)592 })593594 it("does support instanceof Map", () => {595 const map = new Map()596 produce(map, d => {597 expect(d instanceof Map).toBeTruthy()598 })599 })600601 it("handles clear correctly", () => {602 const map = new Map([603 ["a", 1],604 ["c", 3]605 ])606 const next = produce(map, draft => {607 draft.delete("a")608 draft.set("b", 2)609 draft.set("c", 4)610 draft.clear()611 })612 expect(next).toEqual(new Map())613 })614 })615616 describe("set drafts", () => {617 it("supports iteration", () => {618 const base = new Set([619 {id: 1, a: 1},620 {id: 2, a: 1}621 ])622 const findById = (set, id) => {623 for (const item of set) {624 if (item.id === id) return item625 }626 return null627 }628 const result = produce(base, draft => {629 const obj1 = findById(draft, 1)630 const obj2 = findById(draft, 2)631 obj1.a = 2632 obj2.a = 2633 })634 expect(result).not.toBe(base)635 expect(base).toEqual(636 new Set([637 {id: 1, a: 1},638 {id: 2, a: 1}639 ])640 )641 expect(result).toEqual(642 new Set([643 {id: 1, a: 2},644 {id: 2, a: 2}645 ])646 )647 })648649 it("supports 'entries'", () => {650 const base = new Set([651 {id: 1, a: 1},652 {id: 2, a: 1}653 ])654 const findById = (set, id) => {655 for (const [item1, item2] of set.entries()) {656 expect(item1).toBe(item2)657 if (item1.id === id) return item1658 }659 return null660 }661 const result = produce(base, draft => {662 const obj1 = findById(draft, 1)663 const obj2 = findById(draft, 2)664 obj1.a = 2665 obj2.a = 2666 })667 expect(result).not.toBe(base)668 expect(base).toEqual(669 new Set([670 {id: 1, a: 1},671 {id: 2, a: 1}672 ])673 )674 expect(result).toEqual(675 new Set([676 {id: 1, a: 2},677 {id: 2, a: 2}678 ])679 )680 })681682 it("supports 'values'", () => {683 const base = new Set([684 {id: 1, a: 1},685 {id: 2, a: 1}686 ])687 const findById = (set, id) => {688 for (const item of set.values()) {689 if (item.id === id) return item690 }691 return null692 }693 const result = produce(base, draft => {694 const obj1 = findById(draft, 1)695 const obj2 = findById(draft, 2)696 obj1.a = 2697 obj2.a = 2698 })699 expect(result).not.toBe(base)700 expect(base).toEqual(701 new Set([702 {id: 1, a: 1},703 {id: 2, a: 1}704 ])705 )706 expect(result).toEqual(707 new Set([708 {id: 1, a: 2},709 {id: 2, a: 2}710 ])711 )712 })713714 it("supports 'keys'", () => {715 const base = new Set([716 {id: 1, a: 1},717 {id: 2, a: 1}718 ])719 const findById = (set, id) => {720 for (const item of set.keys()) {721 if (item.id === id) return item722 }723 return null724 }725 const result = produce(base, draft => {726 const obj1 = findById(draft, 1)727 const obj2 = findById(draft, 2)728 obj1.a = 2729 obj2.a = 2730 })731 expect(result).not.toBe(base)732 expect(base).toEqual(733 new Set([734 {id: 1, a: 1},735 {id: 2, a: 1}736 ])737 )738 expect(result).toEqual(739 new Set([740 {id: 1, a: 2},741 {id: 2, a: 2}742 ])743 )744 })745746 it("supports forEach with mutation after reads", () => {747 const base = new Set([748 {id: 1, a: 1},749 {id: 2, a: 2}750 ])751 const result = produce(base, draft => {752 let sum1 = 0753 draft.forEach(({a}) => {754 sum1 += a755 })756 expect(sum1).toBe(3)757 let sum2 = 0758 draft.forEach(item => {759 item.a += 10760 sum2 += item.a761 })762 expect(sum2).toBe(23)763 })764 expect(result).not.toBe(base)765 expect(base).toEqual(766 new Set([767 {id: 1, a: 1},768 {id: 2, a: 2}769 ])770 )771 expect(result).toEqual(772 new Set([773 {id: 1, a: 11},774 {id: 2, a: 12}775 ])776 )777 })778779 it("state stays the same if the same item is added", () => {780 const nextState = produce(baseState, s => {781 s.aSet.add("Luke")782 })783 expect(nextState).toBe(baseState)784 expect(nextState.aSet).toBe(baseState.aSet)785 })786787 it("can add new items", () => {788 const nextState = produce(baseState, s => {789 // Set.prototype.set should return the Set itself790 const res = s.aSet.add("force")791 if (!global.USES_BUILD) expect(res).toBe(s.aSet[DRAFT_STATE].draft_)792 })793 expect(nextState).not.toBe(baseState)794 expect(nextState.aSet).not.toBe(baseState.aSet)795 expect(baseState.aSet.has("force")).toBe(false)796 expect(nextState.aSet.has("force")).toBe(true)797 })798799 it("returns 'size'", () => {800 const nextState = produce(baseState, s => {801 s.aSet.add("newKey")802 expect(s.aSet.size).toBe(baseState.aSet.size + 1)803 })804 expect(nextState).not.toBe(baseState)805 expect(nextState.aSet).not.toBe(baseState.aSet)806 expect(nextState.aSet.has("newKey")).toBe(true)807 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)808 })809810 it("can use 'delete' to remove items", () => {811 const nextState = produce(baseState, s => {812 expect(s.aSet.has("Luke")).toBe(true)813 expect(s.aSet.delete("Luke")).toBe(true)814 expect(s.aSet.delete("Luke")).toBe(false)815 expect(s.aSet.has("Luke")).toBe(false)816 })817 expect(nextState.aSet).not.toBe(baseState.aSet)818 expect(baseState.aSet.has("Luke")).toBe(true)819 expect(nextState.aSet.has("Luke")).toBe(false)820 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)821 })822823 it("can use 'clear' to remove items", () => {824 const nextState = produce(baseState, s => {825 expect(s.aSet.size).not.toBe(0)826 s.aSet.clear()827 expect(s.aSet.size).toBe(0)828 })829 expect(nextState.aSet).not.toBe(baseState.aSet)830 expect(baseState.aSet.size).not.toBe(0)831 expect(nextState.aSet.size).toBe(0)832 })833834 it("supports 'has'", () => {835 const nextState = produce(baseState, s => {836 expect(s.aSet.has("newKey")).toBe(false)837 s.aSet.add("newKey")838 expect(s.aSet.has("newKey")).toBe(true)839 })840 expect(nextState).not.toBe(baseState)841 expect(nextState.aSet).not.toBe(baseState.aSet)842 expect(baseState.aSet.has("newKey")).toBe(false)843 expect(nextState.aSet.has("newKey")).toBe(true)844 })845846 it("supports nested sets", () => {847 const base = new Set([new Set(["Serenity"])])848 const result = produce(base, draft => {849 draft.forEach(nestedItem => nestedItem.add("Firefly"))850 })851 expect(result).not.toBe(base)852 expect(base).toEqual(new Set([new Set(["Serenity"])]))853 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))854 })855856 it("supports has / delete on elements from the original", () => {857 const obj = {}858 const set = new Set([obj])859 const next = produce(set, d => {860 expect(d.has(obj)).toBe(true)861 d.add(3)862 expect(d.has(obj)).toBe(true)863 d.delete(obj)864 expect(d.has(obj)).toBe(false)865 })866 expect(next).toEqual(new Set([3]))867 })868869 it("revokes sets", () => {870 let m871 produce(baseState, s => {872 m = s.aSet873 })874 expect(() => m.has("x")).toThrowErrorMatchingSnapshot()875 expect(() => m.add("x")).toThrowErrorMatchingSnapshot()876 })877878 it("does support instanceof Set", () => {879 const set = new Set()880 produce(set, d => {881 expect(d instanceof Set).toBeTruthy()882 })883 })884 })885886 it("supports `immerable` symbol on constructor", () => {887 class One {}888 One[immerable] = true889 const baseState = new One()890 const nextState = produce(baseState, draft => {891 expect(draft).not.toBe(baseState)892 draft.foo = true893 })894 expect(nextState).not.toBe(baseState)895 expect(nextState.foo).toBeTruthy()896 })897898 it("preserves symbol properties", () => {899 const test = Symbol("test")900 const baseState = {[test]: true}901 const nextState = produce(baseState, s => {902 expect(s[test]).toBeTruthy()903 s.foo = true904 })905 expect(nextState).toEqual({906 [test]: true,907 foo: true908 })909 })910911 if (!global.USES_BUILD)912 it("preserves non-enumerable properties", () => {913 const baseState = {}914 // Non-enumerable object property915 Object.defineProperty(baseState, "foo", {916 value: {a: 1},917 enumerable: false918 })919 // Non-enumerable primitive property920 Object.defineProperty(baseState, "bar", {921 value: 1,922 enumerable: false923 })924 const nextState = produce(baseState, s => {925 expect(s.foo).toBeTruthy()926 expect(isEnumerable(s, "foo")).toBeFalsy()927 s.bar++928 expect(isEnumerable(s, "foo")).toBeFalsy()929 s.foo.a++930 expect(isEnumerable(s, "foo")).toBeFalsy()931 })932 expect(nextState.foo).toBeTruthy()933 expect(isEnumerable(nextState, "foo")).toBeFalsy()934 })935936 it("can work with own computed props", () => {937 const baseState = {938 x: 1,939 get y() {940 return this.x941 },942 set y(v) {943 this.x = v944 }945 }946947 const nextState = produce(baseState, d => {948 expect(d.y).toBe(1)949 d.x = 2950 expect(d.x).toBe(2)951 expect(d.y).toBe(1) // this has been copied!952 d.y = 3953 expect(d.x).toBe(2)954 })955 expect(baseState.x).toBe(1)956 expect(baseState.y).toBe(1)957958 expect(nextState.x).toBe(2)959 expect(nextState.y).toBe(3)960 if (!autoFreeze) {961 nextState.y = 4 // decoupled now!962 expect(nextState.y).toBe(4)963 expect(nextState.x).toBe(2)964 expect(Object.getOwnPropertyDescriptor(nextState, "y").value).toBe(4)965 }966 })967968 it("can work with class with computed props", () => {969 class State {970 [immerable] = true971972 x = 1973974 set y(v) {975 this.x = v976 }977978 get y() {979 return this.x980 }981 }982983 const baseState = new State()984985 const nextState = produce(baseState, d => {986 expect(d.y).toBe(1)987 d.y = 2988 expect(d.x).toBe(2)989 expect(d.y).toBe(2)990 expect(Object.getOwnPropertyDescriptor(d, "y")).toBeUndefined()991 })992 expect(baseState.x).toBe(1)993 expect(baseState.y).toBe(1)994995 expect(nextState.x).toBe(2)996 expect(nextState.y).toBe(2)997 expect(Object.getOwnPropertyDescriptor(nextState, "y")).toBeUndefined()998 })9991000 it("allows inherited computed properties", () => {1001 const proto = {}1002 Object.defineProperty(proto, "foo", {1003 get() {1004 return this.bar1005 },1006 set(val) {1007 this.bar = val1008 }1009 })1010 proto[immerable] = true1011 const baseState = Object.create(proto)1012 produce(baseState, s => {1013 expect(s.bar).toBeUndefined()1014 s.foo = {}1015 expect(s.bar).toBeDefined()1016 expect(s.foo).toBe(s.bar)1017 })1018 })10191020 it("optimization: does not visit properties of new data structures if autofreeze is disabled and no drafts are unfinalized", () => {1021 const newData = {}1022 Object.defineProperty(newData, "x", {1023 enumerable: true,1024 get() {1025 throw new Error("visited!")1026 }1027 })10281029 const run = () =>1030 produce({}, d => {1031 d.data = newData1032 })1033 if (autoFreeze) {1034 expect(run).toThrow("visited!")1035 } else {1036 expect(run).not.toThrow("visited!")1037 }1038 })10391040 it("same optimization doesn't cause draft from nested producers to be unfinished", () => {1041 const base = {1042 y: 1,1043 child: {1044 x: 11045 }1046 }1047 const wrap = produce(draft => {1048 return {1049 wrapped: draft1050 }1051 })10521053 const res = produce(base, draft => {1054 draft.y++1055 draft.child = wrap(draft.child)1056 draft.child.wrapped.x++1057 })10581059 expect(res).toEqual({1060 y: 2,1061 child: {wrapped: {x: 2}}1062 })1063 })10641065 it("supports a base state with multiple references to an object", () => {1066 const obj = {}1067 const res = produce({a: obj, b: obj}, d => {1068 // Two drafts are created for each occurrence of an object in the base state.1069 expect(d.a).not.toBe(d.b)1070 d.a.z = true1071 expect(d.b.z).toBeUndefined()1072 })1073 expect(res.b).toBe(obj)1074 expect(res.a).not.toBe(res.b)1075 expect(res.a.z).toBeTruthy()1076 })10771078 // NOTE: Except the root draft.1079 it("supports multiple references to any modified draft", () => {1080 const next = produce({a: {b: 1}}, d => {1081 d.a.b++1082 d.b = d.a1083 })1084 expect(next.a).toBe(next.b)1085 })10861087 it("can rename nested objects (no changes)", () => {1088 const nextState = produce({obj: {}}, s => {1089 s.foo = s.obj1090 delete s.obj1091 })1092 expect(nextState).toEqual({foo: {}})1093 })10941095 // Very similar to the test before, but the reused object has one1096 // property changed, one added, and one removed.1097 it("can rename nested objects (with changes)", () => {1098 const nextState = produce({obj: {a: 1, b: 1}}, s => {1099 s.obj.a = true // change1100 delete s.obj.b // delete1101 s.obj.c = true // add11021103 s.foo = s.obj1104 delete s.obj1105 })1106 expect(nextState).toEqual({foo: {a: true, c: true}})1107 })11081109 it("can nest a draft in a new object (no changes)", () => {1110 const baseState = {obj: {}}1111 const nextState = produce(baseState, s => {1112 s.foo = {bar: s.obj}1113 delete s.obj1114 })1115 expect(nextState.foo.bar).toBe(baseState.obj)1116 })11171118 it("can nest a modified draft in a new object", () => {1119 const nextState = produce({obj: {a: 1, b: 1}}, s => {1120 s.obj.a = true // change1121 delete s.obj.b // delete1122 s.obj.c = true // add11231124 s.foo = {bar: s.obj}1125 delete s.obj1126 })1127 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1128 })11291130 it("supports assigning undefined to an existing property", () => {1131 const nextState = produce(baseState, s => {1132 s.aProp = undefined1133 })1134 expect(nextState).not.toBe(baseState)1135 expect(nextState.aProp).toBe(undefined)1136 })11371138 it("supports assigning undefined to a new property", () => {1139 const baseState = {}1140 const nextState = produce(baseState, s => {1141 s.aProp = undefined1142 })1143 expect(nextState).not.toBe(baseState)1144 expect(nextState.aProp).toBe(undefined)1145 })11461147 // NOTE: ES5 drafts only protect existing properties when revoked.1148 it("revokes the draft once produce returns", () => {1149 const expectRevoked = (fn, shouldThrow = true) => {1150 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()1151 else expect(fn).not.toThrow()1152 }11531154 // Test object drafts:1155 let draft1156 produce({a: 1, b: 1}, s => {1157 draft = s1158 delete s.b1159 })11601161 // Access known property on object draft.1162 expectRevoked(() => {1163 draft.a1164 })11651166 // Assign known property on object draft.1167 expectRevoked(() => {1168 draft.a = true1169 })11701171 // Access unknown property on object draft.1172 expectRevoked(() => {1173 draft.z1174 }, useProxies)11751176 // Assign unknown property on object draft.1177 expectRevoked(() => {1178 draft.z = true1179 }, useProxies)11801181 // Test array drafts:1182 produce([1, 2], s => {1183 draft = s1184 s.pop()1185 })11861187 // Access known index of an array draft.1188 expectRevoked(() => {1189 draft[0]1190 })11911192 // Assign known index of an array draft.1193 expectRevoked(() => {1194 draft[0] = true1195 })11961197 // Access unknown index of an array draft.1198 expectRevoked(() => {1199 draft[1]1200 }, useProxies)12011202 // Assign unknown index of an array draft.1203 expectRevoked(() => {1204 draft[1] = true1205 }, useProxies)1206 })12071208 it("can access a child draft that was created before the draft was modified", () => {1209 produce({a: {}}, s => {1210 const before = s.a1211 s.b = 11212 expect(s.a).toBe(before)1213 })1214 })12151216 it("should reflect all changes made in the draft immediately", () => {1217 produce(baseState, draft => {1218 draft.anArray[0] = 51219 draft.anArray.unshift("test")1220 if (!global.USES_BUILD)1221 expect(enumerableOnly(draft.anArray)).toEqual([1222 "test",1223 5,1224 2,1225 {c: 3},1226 11227 ])1228 draft.stuffz = "coffee"1229 expect(draft.stuffz).toBe("coffee")1230 })1231 })12321233 if (useProxies)1234 it("throws when Object.defineProperty() is used on drafts", () => {1235 expect(() => {1236 produce({}, draft => {1237 Object.defineProperty(draft, "xx", {1238 enumerable: true,1239 writeable: true,1240 value: 21241 })1242 })1243 }).toThrowErrorMatchingSnapshot()1244 })12451246 it("should handle constructor correctly", () => {1247 const baseState = {1248 arr: new Array(),1249 obj: new Object()1250 }1251 const result = produce(baseState, draft => {1252 draft.arrConstructed = draft.arr.constructor(1)1253 draft.objConstructed = draft.obj.constructor(1)1254 })1255 expect(result.arrConstructed).toEqual(new Array().constructor(1))1256 expect(result.objConstructed).toEqual(new Object().constructor(1))1257 })12581259 it("should handle equality correctly - 1", () => {1260 const baseState = {1261 y: 3 / 0,1262 z: NaN1263 }1264 const nextState = produce(baseState, draft => {1265 draft.y = 4 / 01266 draft.z = NaN1267 })1268 expect(nextState).toBe(baseState)1269 })12701271 it("should handle equality correctly - 2", () => {1272 const baseState = {1273 x: -01274 }1275 const nextState = produce(baseState, draft => {1276 draft.x = +01277 })1278 expect(nextState).not.toBe(baseState)1279 expect(nextState).not.toEqual(baseState)1280 })12811282 // AKA: recursive produce calls1283 describe("nested producers", () => {1284 describe("when base state is not a draft", () => {1285 // This test ensures the global state used to manage proxies is1286 // never left in a corrupted state by a nested `produce` call.1287 it("never affects its parent producer implicitly", () => {1288 const base = {obj: {a: 1}}1289 const next = produce(base, draft => {1290 // Notice how `base.obj` is passed, not `draft.obj`1291 const obj2 = produce(base.obj, draft2 => {1292 draft2.a = 01293 })1294 expect(obj2.a).toBe(0)1295 expect(draft.obj.a).toBe(1) // effects should not be visible outside1296 })1297 expect(next).toBe(base)1298 })1299 })13001301 describe("when base state is a draft", () => {1302 it("always wraps the draft in a new draft", () => {1303 produce({}, parent => {1304 produce(parent, child => {1305 expect(child).not.toBe(parent)1306 expect(isDraft(child)).toBeTruthy()1307 expect(original(child)).toBe(parent)1308 })1309 })1310 })13111312 // Reported by: https://github.com/mweststrate/immer/issues/3431313 it("ensures each property is drafted", () => {1314 produce({a: {}, b: {}}, parent => {1315 parent.a // Access "a" but not "b"1316 produce(parent, child => {1317 child.c = 11318 expect(isDraft(child.a)).toBeTruthy()1319 expect(isDraft(child.b)).toBeTruthy()1320 })1321 })1322 })13231324 it("preserves any pending changes", () => {1325 produce({a: 1, b: 1, d: 1}, parent => {1326 parent.b = 21327 parent.c = 21328 delete parent.d1329 produce(parent, child => {1330 expect(child.a).toBe(1) // unchanged1331 expect(child.b).toBe(2) // changed1332 expect(child.c).toBe(2) // added1333 expect(child.d).toBeUndefined() // deleted1334 })1335 })1336 })1337 })13381339 describe("when base state contains a draft", () => {1340 it("wraps unowned draft with its own draft", () => {1341 produce({a: {}}, parent => {1342 produce({a: parent.a}, child => {1343 expect(child.a).not.toBe(parent.a)1344 expect(isDraft(child.a)).toBeTruthy()1345 expect(original(child.a)).toBe(parent.a)1346 })1347 })1348 })13491350 it("returns unowned draft if no changes were made", () => {1351 produce({a: {}}, parent => {1352 const result = produce({a: parent.a}, () => {})1353 expect(result.a).toBe(parent.a)1354 })1355 })13561357 it("clones the unowned draft when changes are made", () => {1358 produce({a: {}}, parent => {1359 const result = produce({a: parent.a}, child => {1360 child.a.b = 11361 })1362 expect(result.a).not.toBe(parent.a)1363 expect(result.a.b).toBe(1)1364 expect("b" in parent.a).toBeFalsy()1365 })1366 })13671368 // We cannot auto-freeze the result of a nested producer,1369 // because it may contain a draft from a parent producer.1370 it("never auto-freezes the result", () => {1371 produce({a: {}}, parent => {1372 const r = produce({a: parent.a}, child => {1373 child.b = 1 // Ensure a copy is returned.1374 })1375 expect(Object.isFrozen(r)).toBeFalsy()1376 })1377 })1378 })13791380 // "Upvalues" are variables from a parent scope.1381 it("does not finalize upvalue drafts", () => {1382 produce({a: {}, b: {}}, parent => {1383 expect(produce({}, () => parent)).toBe(parent)1384 parent.x // Ensure proxy not revoked.13851386 expect(produce({}, () => [parent])[0]).toBe(parent)1387 parent.x // Ensure proxy not revoked.13881389 expect(produce({}, () => parent.a)).toBe(parent.a)1390 parent.a.x // Ensure proxy not revoked.13911392 // Modified parent test1393 parent.c = 11394 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1395 parent.b.x // Ensure proxy not revoked.1396 })1397 })13981399 it("works with interweaved Immer instances", () => {1400 const options = {useProxies, autoFreeze}1401 const one = createPatchedImmer(options)1402 const two = createPatchedImmer(options)14031404 const base = {}1405 const result = one.produce(base, s1 =>1406 two.produce({s1}, s2 => {1407 expect(original(s2.s1)).toBe(s1)1408 s2.n = 11409 s2.s1 = one.produce({s2}, s3 => {1410 expect(original(s3.s2)).toBe(s2)1411 expect(original(s3.s2.s1)).toBe(s2.s1)1412 return s3.s2.s11413 })1414 })1415 )1416 expect(result.n).toBe(1)1417 expect(result.s1).toBe(base)1418 })1419 })14201421 if (useProxies)1422 it("throws when Object.setPrototypeOf() is used on a draft", () => {1423 produce({}, draft => {1424 expect(() =>1425 Object.setPrototypeOf(draft, Array)1426 ).toThrowErrorMatchingSnapshot()1427 })1428 })14291430 it("supports the 'in' operator", () => {1431 produce(baseState, draft => {1432 // Known property1433 expect("anArray" in draft).toBe(true)1434 expect(Reflect.has(draft, "anArray")).toBe(true)14351436 // Unknown property1437 expect("bla" in draft).toBe(false)1438 expect(Reflect.has(draft, "bla")).toBe(false)14391440 // Known index1441 expect(0 in draft.anArray).toBe(true)1442 expect("0" in draft.anArray).toBe(true)1443 expect(Reflect.has(draft.anArray, 0)).toBe(true)1444 expect(Reflect.has(draft.anArray, "0")).toBe(true)14451446 // Unknown index1447 expect(17 in draft.anArray).toBe(false)1448 expect("17" in draft.anArray).toBe(false)1449 expect(Reflect.has(draft.anArray, 17)).toBe(false)1450 expect(Reflect.has(draft.anArray, "17")).toBe(false)1451 })1452 })14531454 it("'this' should not be bound anymore - 1", () => {1455 const base = {x: 3}1456 const next1 = produce(base, function() {1457 expect(this).toBe(undefined)1458 })1459 })14601461 it("'this' should not be bound anymore - 2", () => {1462 const incrementor = produce(function() {1463 expect(this).toBe(undefined)1464 })1465 incrementor()1466 })14671468 it("should be possible to use dynamic bound this", () => {1469 const world = {1470 counter: {count: 1},1471 inc: produce(function(draft) {1472 expect(this).toBe(world)1473 draft.counter.count = this.counter.count + 11474 })1475 }14761477 expect(world.inc(world).counter.count).toBe(2)1478 })14791480 it("doesnt recurse into frozen structures if external data is frozen", () => {1481 const frozen = {}1482 Object.defineProperty(frozen, "x", {1483 get() {1484 throw "oops"1485 },1486 enumerable: true,1487 configurable: true1488 })1489 Object.freeze(frozen)14901491 expect(() => {1492 produce({}, d => {1493 d.x = frozen1494 })1495 }).not.toThrow()1496 })14971498 // See here: https://github.com/mweststrate/immer/issues/891499 it("supports the spread operator", () => {1500 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1501 const result = produce(base, draft => {1502 draft.foo = {x: 1, ...draft.foo, y: 1}1503 draft.bar = [1, ...draft.bar, 1]1504 })1505 expect(result).toEqual({1506 foo: {x: 0, y: 1},1507 bar: [1, 0, 0, 1]1508 })1509 })15101511 it("processes with lodash.set", () => {1512 const base = [{id: 1, a: 1}]1513 const result = produce(base, draft => {1514 lodash.set(draft, "[0].a", 2)1515 })1516 expect(base[0].a).toEqual(1)1517 expect(result[0].a).toEqual(2)1518 })15191520 it("processes with lodash.find", () => {1521 const base = [{id: 1, a: 1}]1522 const result = produce(base, draft => {1523 const obj1 = lodash.find(draft, {id: 1})1524 lodash.set(obj1, "a", 2)1525 })1526 expect(base[0].a).toEqual(1)1527 expect(result[0].a).toEqual(2)1528 })15291530 it("does not draft external data", () => {1531 const externalData = {x: 3}1532 const base = {}1533 const next = produce(base, draft => {1534 // potentially, we *could* draft external data automatically, but only if those statements are not switched...1535 draft.y = externalData1536 draft.y.x += 11537 externalData.x += 11538 })1539 expect(next).toEqual({y: {x: 5}})1540 expect(externalData.x).toBe(5)1541 expect(next.y).toBe(externalData)1542 })15431544 it("does not create new state unnecessary, #491", () => {1545 const a = {highlight: true}1546 const next1 = produce(a, draft => {1547 draft.highlight = false1548 draft.highlight = true1549 })1550 // See explanation in issue1551 expect(next1).not.toBe(a)15521553 const next2 = produce(a, draft => {1554 draft.highlight = true1555 })1556 expect(next2).toBe(a)1557 })15581559 autoFreeze &&1560 test("issue #462 - frozen", () => {1561 var origin = {1562 a: {1563 value: "no"1564 },1565 b: {1566 value: "no"1567 }1568 }1569 const next = produce(origin, draft => {1570 draft.a.value = "im"1571 })1572 expect(() => {1573 origin.b.value = "yes"1574 }).toThrowError(1575 "Cannot assign to read only property 'value' of object '#<Object>'"1576 )1577 expect(() => {1578 next.b.value = "yes"1579 }).toThrowError(1580 "Cannot assign to read only property 'value' of object '#<Object>'"1581 ) // should throw!1582 })15831584 autoFreeze &&1585 test("issue #469, state not frozen", () => {1586 const project = produce(1587 {1588 id: 1,1589 tracks: [{id: 1}]1590 },1591 () => {}1592 )15931594 expect(() => {1595 project.id = 2 // Does not throw error1596 }).toThrowError("Cannot assign to read only property 'id'")15971598 expect(() => {1599 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1600 }).toThrowError("Cannot assign to read only property 'id'")1601 })16021603 describe("recipe functions", () => {1604 it("can return a new object", () => {1605 const base = {x: 3}1606 const res = produce(base, d => {1607 return {x: d.x + 1}1608 })1609 expect(res).not.toBe(base)1610 expect(res).toEqual({x: 4})1611 })16121613 it("can return the draft", () => {1614 const base = {x: 3}1615 const res = produce(base, d => {1616 d.x = 41617 return d1618 })1619 expect(res).not.toBe(base)1620 expect(res).toEqual({x: 4})1621 })16221623 it("can return an unmodified child draft", () => {1624 const base = {a: {}}1625 const res = produce(base, d => {1626 return d.a1627 })1628 expect(res).toBe(base.a)1629 })16301631 // TODO: Avoid throwing if only the child draft was modified.1632 it("cannot return a modified child draft", () => {1633 const base = {a: {}}1634 expect(() => {1635 produce(base, d => {1636 d.a.b = 11637 return d.a1638 })1639 }).toThrowErrorMatchingSnapshot()1640 })16411642 it("can return a frozen object", () => {1643 const res = deepFreeze([{x: 3}])1644 expect(produce({}, () => res)).toBe(res)1645 })16461647 it("can return an object with two references to another object", () => {1648 const next = produce({}, d => {1649 const obj = {}1650 return {obj, arr: [obj]}1651 })1652 expect(next.obj).toBe(next.arr[0])1653 })16541655 it("can return an object with two references to an unmodified draft", () => {1656 const base = {a: {}}1657 const next = produce(base, d => {1658 return [d.a, d.a]1659 })1660 expect(next[0]).toBe(base.a)1661 expect(next[0]).toBe(next[1])1662 })16631664 it("cannot return an object that references itself", () => {1665 const res = {}1666 res.self = res1667 expect(() => {1668 produce(res, () => res.self)1669 }).toThrowErrorMatchingSnapshot()1670 })1671 })16721673 describe("async recipe function", () => {1674 it("can modify the draft", () => {1675 const base = {a: 0, b: 0}1676 return produce(base, async d => {1677 d.a = 11678 await Promise.resolve()1679 d.b = 11680 }).then(res => {1681 expect(res).not.toBe(base)1682 expect(res).toEqual({a: 1, b: 1})1683 })1684 })16851686 it("works with rejected promises", () => {1687 let draft1688 const base = {a: 0, b: 0}1689 const err = new Error("passed")1690 return produce(base, d => {1691 draft = d1692 draft.b = 11693 return Promise.reject(err)1694 }).then(1695 () => {1696 throw "failed"1697 },1698 e => {1699 expect(e).toBe(err)1700 expect(() => draft.a).toThrowErrorMatchingSnapshot()1701 }1702 )1703 })17041705 it("supports recursive produce calls after await", () => {1706 const base = {obj: {k: 1}}1707 return produce(base, d => {1708 const obj = d.obj1709 delete d.obj1710 return Promise.resolve().then(() => {1711 d.a = produce({}, d => {1712 d.b = obj // Assign a draft owned by the parent scope.1713 })17141715 // Auto-freezing is prevented when an unowned draft exists.1716 expect(Object.isFrozen(d.a)).toBeFalsy()17171718 // Ensure `obj` is not revoked.1719 obj.c = 11720 })1721 }).then(res => {1722 expect(res).not.toBe(base)1723 expect(res).toEqual({1724 a: {b: {k: 1, c: 1}}1725 })1726 })1727 })1728 })17291730 it("throws when the draft is modified and another object is returned", () => {1731 const base = {x: 3}1732 expect(() => {1733 produce(base, draft => {1734 draft.x = 41735 return {x: 5}1736 })1737 }).toThrowErrorMatchingSnapshot()1738 })17391740 it("should fix #117 - 1", () => {1741 const reducer = (state, action) =>1742 produce(state, draft => {1743 switch (action.type) {1744 case "SET_STARTING_DOTS":1745 return draft.availableStartingDots.map(a => a)1746 default:1747 break1748 }1749 })1750 const base = {1751 availableStartingDots: [1752 {dots: 4, count: 1},1753 {dots: 3, count: 2},1754 {dots: 2, count: 3},1755 {dots: 1, count: 4}1756 ]1757 }1758 const next = reducer(base, {type: "SET_STARTING_DOTS"})1759 expect(next).toEqual(base.availableStartingDots)1760 expect(next).not.toBe(base.availableStartingDots)1761 })17621763 it("should fix #117 - 2", () => {1764 const reducer = (state, action) =>1765 produce(state, draft => {1766 switch (action.type) {1767 case "SET_STARTING_DOTS":1768 return {1769 dots: draft.availableStartingDots.map(a => a)1770 }1771 default:1772 break1773 }1774 })1775 const base = {1776 availableStartingDots: [1777 {dots: 4, count: 1},1778 {dots: 3, count: 2},1779 {dots: 2, count: 3},1780 {dots: 1, count: 4}1781 ]1782 }1783 const next = reducer(base, {type: "SET_STARTING_DOTS"})1784 expect(next).toEqual({dots: base.availableStartingDots})1785 })17861787 it("cannot always detect noop assignments - 0", () => {1788 const baseState = {x: {y: 3}}1789 const nextState = produce(baseState, d => {1790 const a = d.x1791 d.x = a1792 })1793 expect(nextState).toBe(baseState)1794 })17951796 it("cannot always detect noop assignments - 1", () => {1797 const baseState = {x: {y: 3}}1798 const nextState = produce(baseState, d => {1799 const a = d.x1800 d.x = 41801 d.x = a1802 })1803 // Ideally, this should actually be the same instances1804 // but this would be pretty expensive to detect,1805 // so we don't atm1806 expect(nextState).not.toBe(baseState)1807 })18081809 it("cannot always detect noop assignments - 2", () => {1810 const baseState = {x: {y: 3}}1811 const nextState = produce(baseState, d => {1812 const a = d.x1813 const stuff = a.y + 31814 d.x = 41815 d.x = a1816 })1817 // Ideally, this should actually be the same instances1818 // but this would be pretty expensive to detect,1819 // so we don't atm1820 expect(nextState).not.toBe(baseState)1821 })18221823 it("cannot always detect noop assignments - 3", () => {1824 const baseState = {x: 3}1825 const nextState = produce(baseState, d => {1826 d.x = 31827 })1828 expect(nextState).toBe(baseState)1829 })18301831 it("cannot always detect noop assignments - 4", () => {1832 const baseState = {x: 3}1833 const nextState = produce(baseState, d => {1834 d.x = 41835 d.x = 31836 })1837 // Ideally, this should actually be the same instances1838 // but this would be pretty expensive to detect,1839 // so we don't atm1840 expect(nextState).not.toBe(baseState)1841 })18421843 it("cannot always detect noop assignments - 4", () => {1844 const baseState = {}1845 const [nextState, patches] = produceWithPatches(baseState, d => {1846 d.x = 41847 delete d.x1848 })1849 expect(nextState).toEqual({})1850 expect(patches).toEqual([])1851 // This differs between ES5 and proxy, and ES5 does it better :(1852 if (useProxies) expect(nextState).not.toBe(baseState)1853 else expect(nextState).toBe(baseState)1854 })18551856 it("cannot produce undefined by returning undefined", () => {1857 const base = 31858 expect(produce(base, () => 4)).toBe(4)1859 expect(produce(base, () => null)).toBe(null)1860 expect(produce(base, () => undefined)).toBe(3)1861 expect(produce(base, () => {})).toBe(3)1862 expect(produce(base, () => nothing)).toBe(undefined)18631864 expect(produce({}, () => undefined)).toEqual({})1865 expect(produce({}, () => nothing)).toBe(undefined)1866 expect(produce(3, () => nothing)).toBe(undefined)18671868 expect(produce(() => undefined)({})).toEqual({})1869 expect(produce(() => nothing)({})).toBe(undefined)1870 expect(produce(() => nothing)(3)).toBe(undefined)1871 })18721873 describe("base state type", () => {1874 if (!global.USES_BUILD) testObjectTypes(produce)1875 testLiteralTypes(produce)1876 })18771878 afterEach(() => {1879 expect(baseState).toBe(origBaseState)1880 expect(baseState).toEqual(createBaseState())1881 })18821883 class Foo {}1884 function createBaseState() {1885 const data = {1886 anInstance: new Foo(),1887 anArray: [3, 2, {c: 3}, 1],1888 aMap: new Map([1889 ["jedi", {name: "Luke", skill: 10}],1890 ["jediTotal", 42],1891 ["force", "these aren't the droids you're looking for"]1892 ]),1893 aSet: new Set([1894 "Luke",1895 42,1896 {1897 jedi: "Yoda"1898 }1899 ]),1900 aProp: "hi",1901 anObject: {1902 nested: {1903 yummie: true1904 },1905 coffee: false1906 }1907 }1908 return autoFreeze ? deepFreeze(data) : data1909 }1910 })19111912 it(`works with spread #524 - ${name}`, () => {1913 const state = {1914 level1: {1915 level2: {1916 level3: "data"1917 }1918 }1919 }19201921 const nextState = produce(state, draft => {1922 return {...draft}1923 })1924 const nextState1 = produce(state, draft => {1925 const newLevel1 = produce(draft.level1, level1Draft => {1926 return {...level1Draft}1927 })1928 draft.level1 = newLevel11929 })19301931 const nextState2 = produce(state, draft => {1932 const newLevel1 = produce(draft.level1, level1Draft => {1933 return {...level1Draft}1934 })1935 return {1936 level1: newLevel11937 }1938 })19391940 const nextState3 = produce(state, draft => {1941 const newLevel1 = produce(draft.level1, level1Draft => {1942 return Object.assign({}, level1Draft)1943 })1944 return Object.assign(draft, {1945 level1: newLevel11946 })1947 })19481949 const expected = {level1: {level2: {level3: "data"}}}1950 expect(nextState1).toEqual(expected)1951 expect(nextState2).toEqual(expected)1952 expect(nextState3).toEqual(expected)1953 })19541955 it(`Something with nested producers #522 ${name}`, () => {1956 function initialStateFactory() {1957 return {1958 substate: {1959 array: [1960 {id: "id1", value: 0},1961 {id: "id2", value: 0}1962 ]1963 },1964 array: [1965 {id: "id1", value: 0},1966 {id: "id2", value: 0}1967 ]1968 }1969 }19701971 const globalProducer = produce(draft => {1972 draft.substate = subProducer(draft.substate)1973 draft.array = arrayProducer(draft.array)1974 }, initialStateFactory())19751976 const subProducer = produce(draftSubState => {1977 draftSubState.array = arrayProducer(draftSubState.array)1978 })19791980 const arrayProducer = produce(draftArray => {1981 draftArray[0].value += 51982 })19831984 {1985 const state = globalProducer(undefined)1986 expect(state.array[0].value).toBe(5)1987 expect(state.array.length).toBe(2)1988 expect(state.array[1]).toMatchObject({1989 id: "id2",1990 value: 01991 })1992 }19931994 {1995 const state = globalProducer(undefined)1996 expect(state.substate.array[0].value).toBe(5)1997 expect(state.substate.array.length).toBe(2)1998 expect(state.substate.array[1]).toMatchObject({1999 id: "id2",2000 value: 0The first 2,000 of 2,452 lines.