base.js
This file
Path
__tests__/base.js
1,771 lines · 47.9 KiB · JavaScript
Last changed by
test: tried to reproduce #469Michel Weststratebefore adoptione504e0b
History of this fileTake it
The walk stopped after 200 commits: lines older than 66e51e1 point at it.
feat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
line 1why, one step back1"use strict"feat: limited class supportaleclarsonbefore adoption9877d64
line 2why, one step back2import {Immer, nothing, original, isDraft, immerable} from "../src/index"feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 3why, one step back3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/common"feat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
lines 4–9why, one step back4import deepFreeze from "deep-freeze"5import cloneDeep from "lodash.clonedeep"6import * as lodash from "lodash"78jest.setTimeout(1000)9chore: improve more testsaleclarsonbefore adoption4f59b12
line 10why, one step back10test("immer should have no dependencies", () => {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 11why, one step back11 expect(require("../package.json").dependencies).toBeUndefined()chore: improve more testsaleclarsonbefore adoption4f59b12
line 12why, one step back12})style: use tabsuse-tabsbefore adoptiona9c0fd0
line 13why, one step back13feat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
lines 14–19why, one step back14runBaseTest("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)style: use tabsuse-tabsbefore adoptiona9c0fd0
line 20why, one step back20test: improve tests with Immer classaleclarsonbefore adoptionddc9b40
line 21why, one step back21function runBaseTest(name, useProxies, autoFreeze, useListener) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 22why, one step back22 const listener = useListener ? function() {} : undefinedfeat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 23why, one step back23 const {produce, produceWithPatches} = createPatchedImmer({style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 24–33why, one step back24 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} = immerfeat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 34–35why, one step back34 immer.produce = function(...args) {35 return typeof args[1] === "function" && args.length < 3style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 36–37why, one step back36 ? produce(...args, listener)37 : produce(...args)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 38why, one step back38 }style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 39–302why, one step back3940 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 })302feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 303–714why, one step back303 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 s.aMap.delete("jedi")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 })538 })539540 describe("set drafts", () => {541 it("supports iteration", () => {542 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])543 const findById = (set, id) => {544 for (const item of set) {545 if (item.id === id) return item546 }547 return null548 }549 const result = produce(base, draft => {550 const obj1 = findById(draft, 1)551 const obj2 = findById(draft, 2)552 obj1.a = 2553 obj2.a = 2554 })555 expect(result).not.toBe(base)556 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))557 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))558 })559560 it("supports 'entries'", () => {561 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])562 const findById = (set, id) => {563 for (const [item1, item2] of set.entries()) {564 expect(item1).toBe(item2)565 if (item1.id === id) return item1566 }567 return null568 }569 const result = produce(base, draft => {570 const obj1 = findById(draft, 1)571 const obj2 = findById(draft, 2)572 obj1.a = 2573 obj2.a = 2574 })575 expect(result).not.toBe(base)576 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))577 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))578 })579580 it("supports 'values'", () => {581 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])582 const findById = (set, id) => {583 for (const item of set.values()) {584 if (item.id === id) return item585 }586 return null587 }588 const result = produce(base, draft => {589 const obj1 = findById(draft, 1)590 const obj2 = findById(draft, 2)591 obj1.a = 2592 obj2.a = 2593 })594 expect(result).not.toBe(base)595 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))596 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))597 })598599 it("supports 'keys'", () => {600 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])601 const findById = (set, id) => {602 for (const item of set.keys()) {603 if (item.id === id) return item604 }605 return null606 }607 const result = produce(base, draft => {608 const obj1 = findById(draft, 1)609 const obj2 = findById(draft, 2)610 obj1.a = 2611 obj2.a = 2612 })613 expect(result).not.toBe(base)614 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))615 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))616 })617618 it("supports forEach with mutation after reads", () => {619 const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])620 const result = produce(base, draft => {621 let sum1 = 0622 draft.forEach(({a}) => {623 sum1 += a624 })625 expect(sum1).toBe(3)626 let sum2 = 0627 draft.forEach(item => {628 item.a += 10629 sum2 += item.a630 })631 expect(sum2).toBe(23)632 })633 expect(result).not.toBe(base)634 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 2}]))635 expect(result).toEqual(new Set([{id: 1, a: 11}, {id: 2, a: 12}]))636 })637638 it("state stays the same if the same item is added", () => {639 const nextState = produce(baseState, s => {640 s.aSet.add("Luke")641 })642 expect(nextState).toBe(baseState)643 expect(nextState.aSet).toBe(baseState.aSet)644 })645646 it("can add new items", () => {647 const nextState = produce(baseState, s => {648 // Set.prototype.set should return the Set itself649 const res = s.aSet.add("force")650 expect(res).toBe(s.aSet[DRAFT_STATE].draft)651 })652 expect(nextState).not.toBe(baseState)653 expect(nextState.aSet).not.toBe(baseState.aSet)654 expect(baseState.aSet.has("force")).toBe(false)655 expect(nextState.aSet.has("force")).toBe(true)656 })657658 it("returns 'size'", () => {659 const nextState = produce(baseState, s => {660 s.aSet.add("newKey")661 expect(s.aSet.size).toBe(baseState.aSet.size + 1)662 })663 expect(nextState).not.toBe(baseState)664 expect(nextState.aSet).not.toBe(baseState.aSet)665 expect(nextState.aSet.has("newKey")).toBe(true)666 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)667 })668669 it("can use 'delete' to remove items", () => {670 const nextState = produce(baseState, s => {671 expect(s.aSet.has("Luke")).toBe(true)672 s.aSet.delete("Luke")673 expect(s.aSet.has("Luke")).toBe(false)674 })675 expect(nextState.aSet).not.toBe(baseState.aSet)676 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)677 expect(baseState.aSet.has("Luke")).toBe(true)678 expect(nextState.aSet.has("Luke")).toBe(false)679 })680681 it("can use 'clear' to remove items", () => {682 const nextState = produce(baseState, s => {683 expect(s.aSet.size).not.toBe(0)684 s.aSet.clear()685 expect(s.aSet.size).toBe(0)686 })687 expect(nextState.aSet).not.toBe(baseState.aSet)688 expect(baseState.aSet.size).not.toBe(0)689 expect(nextState.aSet.size).toBe(0)690 })691692 it("supports 'has'", () => {693 const nextState = produce(baseState, s => {694 expect(s.aSet.has("newKey")).toBe(false)695 s.aSet.add("newKey")696 expect(s.aSet.has("newKey")).toBe(true)697 })698 expect(nextState).not.toBe(baseState)699 expect(nextState.aSet).not.toBe(baseState.aSet)700 expect(baseState.aSet.has("newKey")).toBe(false)701 expect(nextState.aSet.has("newKey")).toBe(true)702 })703704 it("supports nested sets", () => {705 const base = new Set([new Set(["Serenity"])])706 const result = produce(base, draft => {707 draft.forEach(nestedItem => nestedItem.add("Firefly"))708 })709 expect(result).not.toBe(base)710 expect(base).toEqual(new Set([new Set(["Serenity"])]))711 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))712 })713 })714style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 715–1238why, one step back715 it("supports `immerable` symbol on constructor", () => {716 class One {}717 One[immerable] = true718 const baseState = new One()719 const nextState = produce(baseState, draft => {720 expect(draft).not.toBe(baseState)721 draft.foo = true722 })723 expect(nextState).not.toBe(baseState)724 expect(nextState.foo).toBeTruthy()725 })726727 it("preserves symbol properties", () => {728 const test = Symbol("test")729 const baseState = {[test]: true}730 const nextState = produce(baseState, s => {731 expect(s[test]).toBeTruthy()732 s.foo = true733 })734 expect(nextState).toEqual({735 [test]: true,736 foo: true737 })738 })739740 it("preserves non-enumerable properties", () => {741 const baseState = {}742 // Non-enumerable object property743 Object.defineProperty(baseState, "foo", {744 value: {a: 1},745 enumerable: false746 })747 // Non-enumerable primitive property748 Object.defineProperty(baseState, "bar", {749 value: 1,750 enumerable: false751 })752 const nextState = produce(baseState, s => {753 expect(s.foo).toBeTruthy()754 expect(isEnumerable(s, "foo")).toBeFalsy()755 s.bar++756 expect(isEnumerable(s, "foo")).toBeFalsy()757 s.foo.a++758 expect(isEnumerable(s, "foo")).toBeFalsy()759 })760 expect(nextState.foo).toBeTruthy()761 expect(isEnumerable(nextState, "foo")).toBeFalsy()762 })763764 it("throws on computed properties", () => {765 const baseState = {}766 Object.defineProperty(baseState, "foo", {767 get: () => {},768 enumerable: true769 })770 expect(() => {771 produce(baseState, s => {772 // Proxies only throw once a change is made.773 if (useProxies) {774 s.modified = true775 }776 })777 }).toThrowErrorMatchingSnapshot()778 })779780 it("allows inherited computed properties", () => {781 const proto = {}782 Object.defineProperty(proto, "foo", {783 get() {784 return this.bar785 },786 set(val) {787 this.bar = val788 }789 })790 const baseState = Object.create(proto)791 produce(baseState, s => {792 expect(s.bar).toBeUndefined()793 s.foo = {}794 expect(s.bar).toBeDefined()795 expect(s.foo).toBe(s.bar)796 })797 })798799 it("supports a base state with multiple references to an object", () => {800 const obj = {}801 const res = produce({a: obj, b: obj}, d => {802 // Two drafts are created for each occurrence of an object in the base state.803 expect(d.a).not.toBe(d.b)804 d.a.z = true805 expect(d.b.z).toBeUndefined()806 })807 expect(res.b).toBe(obj)808 expect(res.a).not.toBe(res.b)809 expect(res.a.z).toBeTruthy()810 })811812 // NOTE: Except the root draft.813 it("supports multiple references to any modified draft", () => {814 const next = produce({a: {b: 1}}, d => {815 d.a.b++816 d.b = d.a817 })818 expect(next.a).toBe(next.b)819 })820821 it("can rename nested objects (no changes)", () => {822 const nextState = produce({obj: {}}, s => {823 s.foo = s.obj824 delete s.obj825 })826 expect(nextState).toEqual({foo: {}})827 })828829 // Very similar to the test before, but the reused object has one830 // property changed, one added, and one removed.831 it("can rename nested objects (with changes)", () => {832 const nextState = produce({obj: {a: 1, b: 1}}, s => {833 s.obj.a = true // change834 delete s.obj.b // delete835 s.obj.c = true // add836837 s.foo = s.obj838 delete s.obj839 })840 expect(nextState).toEqual({foo: {a: true, c: true}})841 })842843 it("can nest a draft in a new object (no changes)", () => {844 const baseState = {obj: {}}845 const nextState = produce(baseState, s => {846 s.foo = {bar: s.obj}847 delete s.obj848 })849 expect(nextState.foo.bar).toBe(baseState.obj)850 })851852 it("can nest a modified draft in a new object", () => {853 const nextState = produce({obj: {a: 1, b: 1}}, s => {854 s.obj.a = true // change855 delete s.obj.b // delete856 s.obj.c = true // add857858 s.foo = {bar: s.obj}859 delete s.obj860 })861 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})862 })863864 it("supports assigning undefined to an existing property", () => {865 const nextState = produce(baseState, s => {866 s.aProp = undefined867 })868 expect(nextState).not.toBe(baseState)869 expect(nextState.aProp).toBe(undefined)870 })871872 it("supports assigning undefined to a new property", () => {873 const baseState = {}874 const nextState = produce(baseState, s => {875 s.aProp = undefined876 })877 expect(nextState).not.toBe(baseState)878 expect(nextState.aProp).toBe(undefined)879 })880881 // NOTE: ES5 drafts only protect existing properties when revoked.882 it("revokes the draft once produce returns", () => {883 const expectRevoked = (fn, shouldThrow = true) => {884 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()885 else expect(fn).not.toThrow()886 }887888 // Test object drafts:889 let draft890 produce({a: 1, b: 1}, s => {891 draft = s892 delete s.b893 })894895 // Access known property on object draft.896 expectRevoked(() => {897 draft.a898 })899900 // Assign known property on object draft.901 expectRevoked(() => {902 draft.a = true903 })904905 // Access unknown property on object draft.906 expectRevoked(() => {907 draft.z908 }, useProxies)909910 // Assign unknown property on object draft.911 expectRevoked(() => {912 draft.z = true913 }, useProxies)914915 // Test array drafts:916 produce([1, 2], s => {917 draft = s918 s.pop()919 })920921 // Access known index of an array draft.922 expectRevoked(() => {923 draft[0]924 })925926 // Assign known index of an array draft.927 expectRevoked(() => {928 draft[0] = true929 })930931 // Access unknown index of an array draft.932 expectRevoked(() => {933 draft[1]934 }, useProxies)935936 // Assign unknown index of an array draft.937 expectRevoked(() => {938 draft[1] = true939 }, useProxies)940 })941942 it("can access a child draft that was created before the draft was modified", () => {943 produce({a: {}}, s => {944 const before = s.a945 s.b = 1946 expect(s.a).toBe(before)947 })948 })949950 it("should reflect all changes made in the draft immediately", () => {951 produce(baseState, draft => {952 draft.anArray[0] = 5953 draft.anArray.unshift("test")954 expect(enumerableOnly(draft.anArray)).toEqual(["test", 5, 2, {c: 3}, 1])955 draft.stuffz = "coffee"956 expect(draft.stuffz).toBe("coffee")957 })958 })959960 if (useProxies)961 it("throws when Object.defineProperty() is used on drafts", () => {962 expect(() => {963 produce({}, draft => {964 Object.defineProperty(draft, "xx", {965 enumerable: true,966 writeable: true,967 value: 2968 })969 })970 }).toThrowErrorMatchingSnapshot()971 })972973 it("should handle constructor correctly", () => {974 const baseState = {975 arr: new Array(),976 obj: new Object()977 }978 const result = produce(baseState, draft => {979 draft.arrConstructed = draft.arr.constructor(1)980 draft.objConstructed = draft.obj.constructor(1)981 })982 expect(result.arrConstructed).toEqual(new Array().constructor(1))983 expect(result.objConstructed).toEqual(new Object().constructor(1))984 })985986 it("should handle equality correctly - 1", () => {987 const baseState = {988 y: 3 / 0,989 z: NaN990 }991 const nextState = produce(baseState, draft => {992 draft.y = 4 / 0993 draft.z = NaN994 })995 expect(nextState).toBe(baseState)996 })997998 it("should handle equality correctly - 2", () => {999 const baseState = {1000 x: -01001 }1002 const nextState = produce(baseState, draft => {1003 draft.x = +01004 })1005 expect(nextState).not.toBe(baseState)1006 expect(nextState).not.toEqual(baseState)1007 })10081009 // AKA: recursive produce calls1010 describe("nested producers", () => {1011 describe("when base state is not a draft", () => {1012 // This test ensures the global state used to manage proxies is1013 // never left in a corrupted state by a nested `produce` call.1014 it("never affects its parent producer implicitly", () => {1015 const base = {obj: {a: 1}}1016 const next = produce(base, draft => {1017 // Notice how `base.obj` is passed, not `draft.obj`1018 const obj2 = produce(base.obj, draft2 => {1019 draft2.a = 01020 })1021 expect(obj2.a).toBe(0)1022 expect(draft.obj.a).toBe(1) // effects should not be visible outside1023 })1024 expect(next).toBe(base)1025 })1026 })10271028 describe("when base state is a draft", () => {1029 it("always wraps the draft in a new draft", () => {1030 produce({}, parent => {1031 produce(parent, child => {1032 expect(child).not.toBe(parent)1033 expect(isDraft(child)).toBeTruthy()1034 expect(original(child)).toBe(parent)1035 })1036 })1037 })10381039 // Reported by: https://github.com/mweststrate/immer/issues/3431040 it("ensures each property is drafted", () => {1041 produce({a: {}, b: {}}, parent => {1042 parent.a // Access "a" but not "b"1043 produce(parent, child => {1044 child.c = 11045 expect(isDraft(child.a)).toBeTruthy()1046 expect(isDraft(child.b)).toBeTruthy()1047 })1048 })1049 })10501051 it("preserves any pending changes", () => {1052 produce({a: 1, b: 1, d: 1}, parent => {1053 parent.b = 21054 parent.c = 21055 delete parent.d1056 produce(parent, child => {1057 expect(child.a).toBe(1) // unchanged1058 expect(child.b).toBe(2) // changed1059 expect(child.c).toBe(2) // added1060 expect(child.d).toBeUndefined() // deleted1061 })1062 })1063 })1064 })10651066 describe("when base state contains a draft", () => {1067 it("wraps unowned draft with its own draft", () => {1068 produce({a: {}}, parent => {1069 produce({a: parent.a}, child => {1070 expect(child.a).not.toBe(parent.a)1071 expect(isDraft(child.a)).toBeTruthy()1072 expect(original(child.a)).toBe(parent.a)1073 })1074 })1075 })10761077 it("returns unowned draft if no changes were made", () => {1078 produce({a: {}}, parent => {1079 const result = produce({a: parent.a}, () => {})1080 expect(result.a).toBe(parent.a)1081 })1082 })10831084 it("clones the unowned draft when changes are made", () => {1085 produce({a: {}}, parent => {1086 const result = produce({a: parent.a}, child => {1087 child.a.b = 11088 })1089 expect(result.a).not.toBe(parent.a)1090 expect(result.a.b).toBe(1)1091 expect("b" in parent.a).toBeFalsy()1092 })1093 })10941095 // We cannot auto-freeze the result of a nested producer,1096 // because it may contain a draft from a parent producer.1097 it("never auto-freezes the result", () => {1098 produce({a: {}}, parent => {1099 const r = produce({a: parent.a}, child => {1100 child.b = 1 // Ensure a copy is returned.1101 })1102 expect(Object.isFrozen(r)).toBeFalsy()1103 })1104 })1105 })11061107 // "Upvalues" are variables from a parent scope.1108 it("does not finalize upvalue drafts", () => {1109 produce({a: {}, b: {}}, parent => {1110 expect(produce({}, () => parent)).toBe(parent)1111 parent.x // Ensure proxy not revoked.11121113 expect(produce({}, () => [parent])[0]).toBe(parent)1114 parent.x // Ensure proxy not revoked.11151116 expect(produce({}, () => parent.a)).toBe(parent.a)1117 parent.a.x // Ensure proxy not revoked.11181119 // Modified parent test1120 parent.c = 11121 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1122 parent.b.x // Ensure proxy not revoked.1123 })1124 })11251126 it("works with interweaved Immer instances", () => {1127 const options = {useProxies, autoFreeze}1128 const one = createPatchedImmer(options)1129 const two = createPatchedImmer(options)11301131 const base = {}1132 const result = one.produce(base, s1 =>1133 two.produce({s1}, s2 => {1134 expect(original(s2.s1)).toBe(s1)1135 s2.n = 11136 s2.s1 = one.produce({s2}, s3 => {1137 expect(original(s3.s2)).toBe(s2)1138 expect(original(s3.s2.s1)).toBe(s2.s1)1139 return s3.s2.s11140 })1141 })1142 )1143 expect(result.n).toBe(1)1144 expect(result.s1).toBe(base)1145 })1146 })11471148 if (useProxies)1149 it("throws when Object.setPrototypeOf() is used on a draft", () => {1150 produce({}, draft => {1151 expect(() =>1152 Object.setPrototypeOf(draft, Array)1153 ).toThrowErrorMatchingSnapshot()1154 })1155 })11561157 it("supports the 'in' operator", () => {1158 produce(baseState, draft => {1159 // Known property1160 expect("anArray" in draft).toBe(true)1161 expect(Reflect.has(draft, "anArray")).toBe(true)11621163 // Unknown property1164 expect("bla" in draft).toBe(false)1165 expect(Reflect.has(draft, "bla")).toBe(false)11661167 // Known index1168 expect(0 in draft.anArray).toBe(true)1169 expect("0" in draft.anArray).toBe(true)1170 expect(Reflect.has(draft.anArray, 0)).toBe(true)1171 expect(Reflect.has(draft.anArray, "0")).toBe(true)11721173 // Unknown index1174 expect(17 in draft.anArray).toBe(false)1175 expect("17" in draft.anArray).toBe(false)1176 expect(Reflect.has(draft.anArray, 17)).toBe(false)1177 expect(Reflect.has(draft.anArray, "17")).toBe(false)1178 })1179 })11801181 it("'this' should not be bound anymore - 1", () => {1182 const base = {x: 3}1183 const next1 = produce(base, function() {1184 expect(this).toBe(undefined)1185 })1186 })11871188 it("'this' should not be bound anymore - 2", () => {1189 const incrementor = produce(function() {1190 expect(this).toBe(undefined)1191 })1192 incrementor()1193 })11941195 it("should be possible to use dynamic bound this", () => {1196 const world = {1197 counter: {count: 1},1198 inc: produce(function(draft) {1199 expect(this).toBe(world)1200 draft.counter.count = this.counter.count + 11201 })1202 }12031204 expect(world.inc(world).counter.count).toBe(2)1205 })12061207 // See here: https://github.com/mweststrate/immer/issues/891208 it("supports the spread operator", () => {1209 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1210 const result = produce(base, draft => {1211 draft.foo = {x: 1, ...draft.foo, y: 1}1212 draft.bar = [1, ...draft.bar, 1]1213 })1214 expect(result).toEqual({1215 foo: {x: 0, y: 1},1216 bar: [1, 0, 0, 1]1217 })1218 })12191220 it("processes with lodash.set", () => {1221 const base = [{id: 1, a: 1}]1222 const result = produce(base, draft => {1223 lodash.set(draft, "[0].a", 2)1224 })1225 expect(base[0].a).toEqual(1)1226 expect(result[0].a).toEqual(2)1227 })12281229 it("processes with lodash.find", () => {1230 const base = [{id: 1, a: 1}]1231 const result = produce(base, draft => {1232 const obj1 = lodash.find(draft, {id: 1})1233 lodash.set(obj1, "a", 2)1234 })1235 expect(base[0].a).toEqual(1)1236 expect(result[0].a).toEqual(2)1237 })1238test: tried to reproduce #469Michel Weststratebefore adoptione504e0b
lines 1239–1257why, one step back1239 autoFreeze &&1240 test("issue #469, state not frozen", () => {1241 const project = produce(1242 {1243 id: 1,1244 tracks: [{id: 1}]1245 },1246 () => {}1247 )12481249 expect(() => {1250 project.id = 2 // Does not throw error1251 }).toThrowError("Cannot assign to read only property 'id'")12521253 expect(() => {1254 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1255 }).toThrowError("Cannot assign to read only property 'id'")1256 })1257style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1258–1529why, one step back1258 describe("recipe functions", () => {1259 it("can return a new object", () => {1260 const base = {x: 3}1261 const res = produce(base, d => {1262 return {x: d.x + 1}1263 })1264 expect(res).not.toBe(base)1265 expect(res).toEqual({x: 4})1266 })12671268 it("can return the draft", () => {1269 const base = {x: 3}1270 const res = produce(base, d => {1271 d.x = 41272 return d1273 })1274 expect(res).not.toBe(base)1275 expect(res).toEqual({x: 4})1276 })12771278 it("can return an unmodified child draft", () => {1279 const base = {a: {}}1280 const res = produce(base, d => {1281 return d.a1282 })1283 expect(res).toBe(base.a)1284 })12851286 // TODO: Avoid throwing if only the child draft was modified.1287 it("cannot return a modified child draft", () => {1288 const base = {a: {}}1289 expect(() => {1290 produce(base, d => {1291 d.a.b = 11292 return d.a1293 })1294 }).toThrowErrorMatchingSnapshot()1295 })12961297 it("can return a frozen object", () => {1298 const res = deepFreeze([{x: 3}])1299 expect(produce({}, () => res)).toBe(res)1300 })13011302 it("can return an object with two references to another object", () => {1303 const next = produce({}, d => {1304 const obj = {}1305 return {obj, arr: [obj]}1306 })1307 expect(next.obj).toBe(next.arr[0])1308 })13091310 it("can return an object with two references to an unmodified draft", () => {1311 const base = {a: {}}1312 const next = produce(base, d => {1313 return [d.a, d.a]1314 })1315 expect(next[0]).toBe(base.a)1316 expect(next[0]).toBe(next[1])1317 })13181319 it("cannot return an object that references itself", () => {1320 const res = {}1321 res.self = res1322 expect(() => {1323 produce(res, () => res.self)1324 }).toThrowErrorMatchingSnapshot()1325 })1326 })13271328 describe("async recipe function", () => {1329 it("can modify the draft", () => {1330 const base = {a: 0, b: 0}1331 return produce(base, async d => {1332 d.a = 11333 await Promise.resolve()1334 d.b = 11335 }).then(res => {1336 expect(res).not.toBe(base)1337 expect(res).toEqual({a: 1, b: 1})1338 })1339 })13401341 it("works with rejected promises", () => {1342 let draft1343 const base = {a: 0, b: 0}1344 const err = new Error("passed")1345 return produce(base, d => {1346 draft = d1347 draft.b = 11348 return Promise.reject(err)1349 }).then(1350 () => {1351 throw "failed"1352 },1353 e => {1354 expect(e).toBe(err)1355 expect(() => draft.a).toThrowErrorMatchingSnapshot()1356 }1357 )1358 })13591360 it("supports recursive produce calls after await", () => {1361 const base = {obj: {k: 1}}1362 return produce(base, d => {1363 const obj = d.obj1364 delete d.obj1365 return Promise.resolve().then(() => {1366 d.a = produce({}, d => {1367 d.b = obj // Assign a draft owned by the parent scope.1368 })13691370 // Auto-freezing is prevented when an unowned draft exists.1371 expect(Object.isFrozen(d.a)).toBeFalsy()13721373 // Ensure `obj` is not revoked.1374 obj.c = 11375 })1376 }).then(res => {1377 expect(res).not.toBe(base)1378 expect(res).toEqual({1379 a: {b: {k: 1, c: 1}}1380 })1381 })1382 })1383 })13841385 it("throws when the draft is modified and another object is returned", () => {1386 const base = {x: 3}1387 expect(() => {1388 produce(base, draft => {1389 draft.x = 41390 return {x: 5}1391 })1392 }).toThrowErrorMatchingSnapshot()1393 })13941395 it("should fix #117 - 1", () => {1396 const reducer = (state, action) =>1397 produce(state, draft => {1398 switch (action.type) {1399 case "SET_STARTING_DOTS":1400 return draft.availableStartingDots.map(a => a)1401 default:1402 break1403 }1404 })1405 const base = {1406 availableStartingDots: [1407 {dots: 4, count: 1},1408 {dots: 3, count: 2},1409 {dots: 2, count: 3},1410 {dots: 1, count: 4}1411 ]1412 }1413 const next = reducer(base, {type: "SET_STARTING_DOTS"})1414 expect(next).toEqual(base.availableStartingDots)1415 expect(next).not.toBe(base.availableStartingDots)1416 })14171418 it("should fix #117 - 2", () => {1419 const reducer = (state, action) =>1420 produce(state, draft => {1421 switch (action.type) {1422 case "SET_STARTING_DOTS":1423 return {1424 dots: draft.availableStartingDots.map(a => a)1425 }1426 default:1427 break1428 }1429 })1430 const base = {1431 availableStartingDots: [1432 {dots: 4, count: 1},1433 {dots: 3, count: 2},1434 {dots: 2, count: 3},1435 {dots: 1, count: 4}1436 ]1437 }1438 const next = reducer(base, {type: "SET_STARTING_DOTS"})1439 expect(next).toEqual({dots: base.availableStartingDots})1440 })14411442 it("cannot always detect noop assignments - 0", () => {1443 const baseState = {x: {y: 3}}1444 const nextState = produce(baseState, d => {1445 const a = d.x1446 d.x = a1447 })1448 expect(nextState).toBe(baseState)1449 })14501451 it("cannot always detect noop assignments - 1", () => {1452 const baseState = {x: {y: 3}}1453 const nextState = produce(baseState, d => {1454 const a = d.x1455 d.x = 41456 d.x = a1457 })1458 // Ideally, this should actually be the same instances1459 // but this would be pretty expensive to detect,1460 // so we don't atm1461 expect(nextState).not.toBe(baseState)1462 })14631464 it("cannot always detect noop assignments - 2", () => {1465 const baseState = {x: {y: 3}}1466 const nextState = produce(baseState, d => {1467 const a = d.x1468 const stuff = a.y + 31469 d.x = 41470 d.x = a1471 })1472 // Ideally, this should actually be the same instances1473 // but this would be pretty expensive to detect,1474 // so we don't atm1475 expect(nextState).not.toBe(baseState)1476 })14771478 it("cannot always detect noop assignments - 3", () => {1479 const baseState = {x: 3}1480 const nextState = produce(baseState, d => {1481 d.x = 31482 })1483 expect(nextState).toBe(baseState)1484 })14851486 it("cannot always detect noop assignments - 4", () => {1487 const baseState = {x: 3}1488 const nextState = produce(baseState, d => {1489 d.x = 41490 d.x = 31491 })1492 // Ideally, this should actually be the same instances1493 // but this would be pretty expensive to detect,1494 // so we don't atm1495 expect(nextState).not.toBe(baseState)1496 })14971498 it("cannot produce undefined by returning undefined", () => {1499 const base = 31500 expect(produce(base, () => 4)).toBe(4)1501 expect(produce(base, () => null)).toBe(null)1502 expect(produce(base, () => undefined)).toBe(3)1503 expect(produce(base, () => {})).toBe(3)1504 expect(produce(base, () => nothing)).toBe(undefined)15051506 expect(produce({}, () => undefined)).toEqual({})1507 expect(produce({}, () => nothing)).toBe(undefined)1508 expect(produce(3, () => nothing)).toBe(undefined)15091510 expect(produce(() => undefined)({})).toEqual({})1511 expect(produce(() => nothing)({})).toBe(undefined)1512 expect(produce(() => nothing)(3)).toBe(undefined)1513 })15141515 describe("base state type", () => {1516 testObjectTypes(produce)1517 testLiteralTypes(produce)1518 })15191520 afterEach(() => {1521 expect(baseState).toBe(origBaseState)1522 expect(baseState).toEqual(createBaseState())1523 })15241525 class Foo {}1526 function createBaseState() {1527 const data = {1528 anInstance: new Foo(),1529 anArray: [3, 2, {c: 3}, 1],feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1530–1541why, one step back1530 aMap: new Map([1531 ["jedi", {name: "Luke", skill: 10}],1532 ["jediTotal", 42],1533 ["force", "these aren't the droids you're looking for"]1534 ]),1535 aSet: new Set([1536 "Luke",1537 42,1538 {1539 jedi: "Yoda"1540 }1541 ]),style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1542–1591why, one step back1542 aProp: "hi",1543 anObject: {1544 nested: {1545 yummie: true1546 },1547 coffee: false1548 }1549 }1550 return autoFreeze ? deepFreeze(data) : data1551 }1552 })15531554 describe(`isDraft - ${name}`, () => {1555 it("returns true for object drafts", () => {1556 produce({}, state => {1557 expect(isDraft(state)).toBeTruthy()1558 })1559 })1560 it("returns true for array drafts", () => {1561 produce([], state => {1562 expect(isDraft(state)).toBeTruthy()1563 })1564 })1565 it("returns true for objects nested in object drafts", () => {1566 produce({a: {b: {}}}, state => {1567 expect(isDraft(state.a)).toBeTruthy()1568 expect(isDraft(state.a.b)).toBeTruthy()1569 })1570 })1571 it("returns false for new objects added to a draft", () => {1572 produce({}, state => {1573 state.a = {}1574 expect(isDraft(state.a)).toBeFalsy()1575 })1576 })1577 it("returns false for objects returned by the producer", () => {1578 const object = produce(null, Object.create)1579 expect(isDraft(object)).toBeFalsy()1580 })1581 it("returns false for arrays returned by the producer", () => {1582 const array = produce(null, _ => [])1583 expect(isDraft(array)).toBeFalsy()1584 })1585 it("returns false for object drafts returned by the producer", () => {1586 const object = produce({}, state => state)1587 expect(isDraft(object)).toBeFalsy()1588 })1589 it("returns false for array drafts returned by the producer", () => {1590 const array = produce([], state => state)1591 expect(isDraft(array)).toBeFalsy()feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1592–1650why, one step back1592 })1593 })15941595 describe(`complex nesting map / set / object`, () => {1596 const a = {a: 1}1597 const b = {b: 2}1598 const c = {c: 3}1599 const set1 = new Set([a, b])1600 const set2 = new Set([c])1601 const map = new Map([["set1", set1], ["set2", set2]])1602 const base = {map}16031604 function first(set) {1605 return Array.from(set.values())[0]1606 }16071608 function second(set) {1609 return Array.from(set.values())[1]1610 }16111612 test(`modify deep object`, () => {1613 const [res, patches] = produceWithPatches(base, draft => {1614 const v = first(draft.map.get("set1"))1615 expect(original(v)).toBe(a)1616 expect(v).toEqual(a)1617 expect(v).not.toBe(a)1618 v.a++1619 })1620 expect(res).toMatchSnapshot()1621 expect(patches).toMatchSnapshot()1622 expect(a.a).toBe(1)1623 expect(base.map.get("set1")).toBe(set1)1624 expect(first(base.map.get("set1"))).toBe(a)1625 expect(res).not.toBe(base)1626 expect(res.map).not.toBe(base.map)1627 expect(res.map.get("set1")).not.toBe(base.map.get("set1"))1628 expect(second(base.map.get("set1"))).toBe(b)1629 expect(base.map.get("set2")).toBe(set2)1630 expect(first(res.map.get("set1"))).toEqual({a: 2})1631 })16321633 test(`modify deep object - keep value`, () => {1634 const [res, patches] = produceWithPatches(base, draft => {1635 const v = first(draft.map.get("set1"))1636 expect(original(v)).toBe(a)1637 expect(v).toEqual(a)1638 expect(v).not.toBe(a)1639 v.a = 1 // same value1640 })1641 expect(a.a).toBe(1)1642 expect(base.map.get("set1")).toBe(set1)1643 expect(first(base.map.get("set1"))).toBe(a)1644 expect(res).toBe(base)1645 expect(res.map).toBe(base.map)1646 expect(res.map.get("set1")).toBe(base.map.get("set1"))1647 expect(first(res.map.get("set1"))).toBe(a)1648 expect(second(base.map.get("set1"))).toBe(b)1649 expect(base.map.get("set2")).toBe(set2)1650 expect(patches.length).toBe(0)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1651–1654why, one step back1651 })1652 })1653}1654chore: improve more testsaleclarsonbefore adoption4f59b12
line 1655why, one step back1655function testObjectTypes(produce) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1656–1708why, one step back1656 class Foo {1657 constructor(foo) {1658 this.foo = foo1659 this[immerable] = true1660 }1661 }1662 const values = {1663 "empty object": {},1664 "plain object": {a: 1, b: 2},1665 "object (no prototype)": Object.create(null),1666 "empty array": [],1667 "plain array": [1, 2],1668 "class instance (draftable)": new Foo(1)1669 }1670 for (const name in values) {1671 const value = values[name]1672 const copy = shallowCopy(value)1673 testObjectType(name, value)1674 testObjectType(name + " (frozen)", Object.freeze(copy))1675 }1676 function testObjectType(name, base) {1677 describe(name, () => {1678 it("creates a draft", () => {1679 produce(base, draft => {1680 expect(draft).not.toBe(base)1681 expect(shallowCopy(draft, true)).toEqual(base)1682 })1683 })16841685 it("preserves the prototype", () => {1686 const proto = Object.getPrototypeOf(base)1687 produce(base, draft => {1688 expect(Object.getPrototypeOf(draft)).toBe(proto)1689 })1690 })16911692 it("returns the base state when no changes are made", () => {1693 expect(produce(base, () => {})).toBe(base)1694 })16951696 it("returns a copy when changes are made", () => {1697 const random = Math.random()1698 const result = produce(base, draft => {1699 draft[0] = random1700 })1701 expect(result).not.toBe(base)1702 expect(result.constructor).toBe(base.constructor)1703 expect(result[0]).toBe(random)1704 })1705 })1706 }1707}1708chore: improve more testsaleclarsonbefore adoption4f59b12
line 1709why, one step back1709function testLiteralTypes(produce) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1710–1762why, one step back1710 class Foo {}1711 const values = {1712 "falsy number": 0,1713 "truthy number": 1,1714 "negative number": -1,1715 NaN: NaN,1716 infinity: 1 / 0,1717 true: true,1718 false: false,1719 "empty string": "",1720 "truthy string": "1",1721 null: null,1722 undefined: undefined,17231724 /**1725 * These objects are treated as literals because Immer1726 * does not know how to draft them.1727 */1728 function: () => {},1729 "regexp object": /.+/g,1730 "boxed number": new Number(0),1731 "boxed string": new String(""),1732 "boxed boolean": new Boolean(),1733 "date object": new Date(),1734 "class instance (not draftable)": new Foo()1735 }1736 for (const name in values) {1737 describe(name, () => {1738 const value = values[name]17391740 it("does not create a draft", () => {1741 produce(value, draft => {1742 expect(draft).toBe(value)1743 })1744 })17451746 it("returns the base state when no changes are made", () => {1747 expect(produce(value, () => {})).toBe(value)1748 })17491750 if (value && typeof value == "object") {1751 it("does not return a copy when changes are made", () => {1752 expect(1753 produce(value, draft => {1754 draft.foo = true1755 })1756 ).toBe(value)1757 })1758 }1759 })1760 }1761}1762feat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
line 1763why, one step back1763function enumerableOnly(x) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1764–1770why, one step back1764 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1765 each(copy, (prop, value) => {1766 if (value && typeof value === "object") {1767 copy[prop] = enumerableOnly(value)1768 }1769 })1770 return copyfeat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
line 1771why, one step back1771}