base.js
This file
Path
__tests__/base.js
1,988 lines · 51.8 KiB · JavaScript
Last changed by
feat: general typing improvements for TS 3.7 and upMichel Weststratebefore adoptionf930ce1
History of this fileTake it
The walk stopped after 200 commits: lines older than 721c488 point at it.
test: rename test.tsconfig.json so vscode can find italeclarsonbefore adoption721c488
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"fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
line 3why, one step back3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/internal"test: rename test.tsconfig.json so vscode can find italeclarsonbefore adoption721c488
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 back13test: rename test.tsconfig.json so vscode can find italeclarsonbefore adoption721c488
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–190why, 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", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 191–194why, one step back191 const base = [192 {id: 1, a: 1},193 {id: 2, a: 1}194 ]style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 195–305why, one step back195 const findById = (collection, id) => {196 for (const item of collection) {197 if (item.id === id) return item198 }199 return null200 }201 const result = produce(base, draft => {202 const obj1 = findById(draft, 1)203 const obj2 = findById(draft, 2)204 obj1.a = 2205 obj2.a = 2206 })207 expect(result[0].a).toEqual(2)208 expect(result[1].a).toEqual(2)209 })210211 it("can assign an index via bracket notation", () => {212 const nextState = produce(baseState, s => {213 s.anArray[3] = true214 })215 expect(nextState).not.toBe(baseState)216 expect(nextState.anArray).not.toBe(baseState.anArray)217 expect(nextState.anArray[3]).toEqual(true)218 })219220 it("can use splice() to both add and remove items", () => {221 const nextState = produce(baseState, s => {222 s.anArray.splice(1, 1, "a", "b")223 })224 expect(nextState.anArray).not.toBe(baseState.anArray)225 expect(nextState.anArray[1]).toBe("a")226 expect(nextState.anArray[2]).toBe("b")227 })228229 it("can truncate via the length property", () => {230 const baseLength = baseState.anArray.length231 const nextState = produce(baseState, s => {232 s.anArray.length = baseLength - 1233 })234 expect(nextState.anArray).not.toBe(baseState.anArray)235 expect(nextState.anArray.length).toBe(baseLength - 1)236 })237238 it("can extend via the length property", () => {239 const baseLength = baseState.anArray.length240 const nextState = produce(baseState, s => {241 s.anArray.length = baseLength + 1242 })243 expect(nextState.anArray).not.toBe(baseState.anArray)244 expect(nextState.anArray.length).toBe(baseLength + 1)245 })246247 // Reported here: https://github.com/mweststrate/immer/issues/116248 it("can pop then push", () => {249 const nextState = produce([1, 2, 3], s => {250 s.pop()251 s.push(100)252 })253 expect(nextState).toEqual([1, 2, 100])254 })255256 it("can be sorted", () => {257 const baseState = [3, 1, 2]258 const nextState = produce(baseState, s => {259 s.sort()260 })261 expect(nextState).not.toBe(baseState)262 expect(nextState).toEqual([1, 2, 3])263 })264265 it("supports modifying nested objects", () => {266 const baseState = [{a: 1}, {}]267 const nextState = produce(baseState, s => {268 s[0].a++269 s[1].a = 0270 })271 expect(nextState).not.toBe(baseState)272 expect(nextState[0].a).toBe(2)273 expect(nextState[1].a).toBe(0)274 })275276 it("never preserves non-numeric properties", () => {277 const baseState = []278 baseState.x = 7279 const nextState = produce(baseState, s => {280 s.push(3)281 })282 expect("x" in nextState).toBeFalsy()283 })284285 if (useProxies) {286 it("throws when a non-numeric property is added", () => {287 expect(() => {288 produce([], d => {289 d.x = 3290 })291 }).toThrowErrorMatchingSnapshot()292 })293294 it("throws when a non-numeric property is deleted", () => {295 expect(() => {296 const baseState = []297 baseState.x = 7298 produce(baseState, d => {299 delete d.x300 })301 }).toThrowErrorMatchingSnapshot()302 })303 }304 })305feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 306–391why, one step back306 describe("map drafts", () => {307 it("supports key access", () => {308 const value = baseState.aMap.get("jedi")309 const nextState = produce(baseState, s => {310 expect(s.aMap.get("jedi")).toEqual(value)311 })312 expect(nextState).toBe(baseState)313 })314315 it("supports key access for non-primitive keys", () => {316 const key = {prop: "val"}317 const base = new Map([[key, {id: 1, a: 1}]])318 const value = base.get(key)319 const nextState = produce(base, s => {320 expect(s.get(key)).toEqual(value)321 })322 expect(nextState).toBe(base)323 })324325 it("supports iteration", () => {326 const base = new Map([327 ["first", {id: 1, a: 1}],328 ["second", {id: 2, a: 1}]329 ])330 const findById = (map, id) => {331 for (const [, item] of map) {332 if (item.id === id) return item333 }334 return null335 }336 const result = produce(base, draft => {337 const obj1 = findById(draft, 1)338 const obj2 = findById(draft, 2)339 obj1.a = 2340 obj2.a = 2341 })342 expect(result).not.toBe(base)343 expect(result.get("first").a).toEqual(2)344 expect(result.get("second").a).toEqual(2)345 })346347 it("supports 'entries'", () => {348 const base = new Map([349 ["first", {id: 1, a: 1}],350 ["second", {id: 2, a: 1}]351 ])352 const findById = (map, id) => {353 for (const [, item] of map.entries()) {354 if (item.id === id) return item355 }356 return null357 }358 const result = produce(base, draft => {359 const obj1 = findById(draft, 1)360 const obj2 = findById(draft, 2)361 obj1.a = 2362 obj2.a = 2363 })364 expect(result).not.toBe(base)365 expect(result.get("first").a).toEqual(2)366 expect(result.get("second").a).toEqual(2)367 })368369 it("supports 'values'", () => {370 const base = new Map([371 ["first", {id: 1, a: 1}],372 ["second", {id: 2, a: 1}]373 ])374 const findById = (map, id) => {375 for (const item of map.values()) {376 if (item.id === id) return item377 }378 return null379 }380 const result = produce(base, draft => {381 const obj1 = findById(draft, 1)382 const obj2 = findById(draft, 2)383 obj1.a = 2384 obj2.a = 2385 })386 expect(result).not.toBe(base)387 expect(result.get("first").a).toEqual(2)388 expect(result.get("second").a).toEqual(2)389 })390391 it("supports 'keys", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 392–395why, one step back392 const base = new Map([393 ["first", Symbol()],394 ["second", Symbol()]395 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 396–498why, one step back396 const result = produce(base, draft => {397 expect([...draft.keys()]).toEqual(["first", "second"])398 draft.set("third", Symbol())399 expect([...draft.keys()]).toEqual(["first", "second", "third"])400 })401 })402403 it("supports forEach", () => {404 const key1 = {prop: "val1"}405 const key2 = {prop: "val2"}406 const base = new Map([407 ["first", {id: 1, a: 1}],408 ["second", {id: 2, a: 1}],409 [key1, {id: 3, a: 1}],410 [key2, {id: 4, a: 1}]411 ])412 const result = produce(base, draft => {413 let sum1 = 0414 draft.forEach(({a}) => {415 sum1 += a416 })417 expect(sum1).toBe(4)418 let sum2 = 0419 draft.get("first").a = 10420 draft.get("second").a = 20421 draft.get(key1).a = 30422 draft.get(key2).a = 40423 draft.forEach(({a}) => {424 sum2 += a425 })426 expect(sum2).toBe(100)427 })428 expect(result).not.toBe(base)429 expect(base.get("first").a).toEqual(1)430 expect(base.get("second").a).toEqual(1)431 expect(base.get(key1).a).toEqual(1)432 expect(base.get(key2).a).toEqual(1)433 expect(result.get("first").a).toEqual(10)434 expect(result.get("second").a).toEqual(20)435 expect(result.get(key1).a).toEqual(30)436 expect(result.get(key2).a).toEqual(40)437 })438439 it("supports forEach mutation", () => {440 const base = new Map([441 ["first", {id: 1, a: 1}],442 ["second", {id: 2, a: 1}]443 ])444 const result = produce(base, draft => {445 draft.forEach(item => {446 item.a = 100447 })448 })449 expect(result).not.toBe(base)450 expect(result.get("first").a).toEqual(100)451 expect(result.get("second").a).toEqual(100)452 })453454 it("can assign by key", () => {455 const nextState = produce(baseState, s => {456 // Map.prototype.set should return the Map itself457 const res = s.aMap.set("force", true)458 expect(res).toBe(s.aMap[DRAFT_STATE].draft)459 })460 expect(nextState).not.toBe(baseState)461 expect(nextState.aMap).not.toBe(baseState.aMap)462 expect(nextState.aMap.get("force")).toEqual(true)463 })464465 it("can assign by a non-primitive key", () => {466 const key = {prop: "val"}467 const value = {id: 1, a: 1}468 const base = new Map([[key, value]])469 const nextState = produce(base, s => {470 s.set(key, true)471 })472 expect(nextState).not.toBe(base)473 expect(base.get(key)).toEqual(value)474 expect(nextState.get(key)).toEqual(true)475 })476477 it("state stays the same if the the same item is assigned by key", () => {478 const nextState = produce(baseState, s => {479 s.aMap.set("jediTotal", 42)480 })481 expect(nextState).toBe(baseState)482 expect(nextState.aMap).toBe(baseState.aMap)483 })484485 it("returns 'size'", () => {486 const nextState = produce(baseState, s => {487 s.aMap.set("newKey", true)488 expect(s.aMap.size).toBe(baseState.aMap.size + 1)489 })490 expect(nextState).not.toBe(baseState)491 expect(nextState.aMap).not.toBe(baseState.aMap)492 expect(nextState.aMap.get("newKey")).toEqual(true)493 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)494 })495496 it("can use 'delete' to remove items", () => {497 const nextState = produce(baseState, s => {498 expect(s.aMap.has("jedi")).toBe(true)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 499why, one step back499 expect(s.aMap.delete("jedi")).toBe(true)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 500–543why, one step back500 expect(s.aMap.has("jedi")).toBe(false)501 })502 expect(nextState.aMap).not.toBe(baseState.aMap)503 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)504 expect(baseState.aMap.has("jedi")).toBe(true)505 expect(nextState.aMap.has("jedi")).toBe(false)506 })507508 it("can use 'clear' to remove items", () => {509 const nextState = produce(baseState, s => {510 expect(s.aMap.size).not.toBe(0)511 s.aMap.clear()512 expect(s.aMap.size).toBe(0)513 })514 expect(nextState.aMap).not.toBe(baseState.aMap)515 expect(baseState.aMap.size).not.toBe(0)516 expect(nextState.aMap.size).toBe(0)517 })518519 it("support 'has'", () => {520 const nextState = produce(baseState, s => {521 expect(s.aMap.has("newKey")).toBe(false)522 s.aMap.set("newKey", true)523 expect(s.aMap.has("newKey")).toBe(true)524 })525 expect(nextState).not.toBe(baseState)526 expect(nextState.aMap).not.toBe(baseState.aMap)527 expect(baseState.aMap.has("newKey")).toBe(false)528 expect(nextState.aMap.has("newKey")).toBe(true)529 })530531 it("supports nested maps", () => {532 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])533 const result = produce(base, draft => {534 draft.get("first").get("second").prop = "test1"535 })536 expect(result).not.toBe(base)537 expect(result.get("first")).not.toBe(base.get("first"))538 expect(result.get("first").get("second")).not.toBe(539 base.get("first").get("second")540 )541 expect(base.get("first").get("second").prop).toBe("test")542 expect(result.get("first").get("second").prop).toBe("test1")543 })feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 544–584why, one step back544545 it("treats void deletes as no-op", () => {546 const base = new Map([["x", 1]])547 const next = produce(base, d => {548 expect(d.delete("y")).toBe(false)549 })550 expect(next).toBe(base)551 })552553 it("revokes map proxies", () => {554 let m555 produce(baseState, s => {556 m = s.aMap557 })558 expect(() => m.get("x")).toThrow(559 "Cannot use a proxy that has been revoked"560 )561 expect(() => m.set("x", 3)).toThrow(562 "Cannot use a proxy that has been revoked"563 )564 })565566 it("does not draft map keys", () => {567 // anything else would be terribly confusing568 const key = {a: 1}569 const map = new Map([[key, 2]])570 const next = produce(map, d => {571 const dKey = Array.from(d.keys())[0]572 expect(isDraft(dKey)).toBe(false)573 expect(dKey).toBe(key)574 dKey.a += 1575 d.set(dKey, d.get(dKey) + 1)576 d.set(key, d.get(key) + 1)577 expect(d.get(key)).toBe(4)578 expect(key.a).toBe(2)579 })580 const entries = Array.from(next.entries())581 expect(entries).toEqual([[key, 4]])582 expect(entries[0][0]).toBe(key)583 expect(entries[0][0].a).toBe(2)584 })fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 585–591why, one step back585586 it("does support instanceof Map", () => {587 const map = new Map()588 produce(map, d => {589 expect(d instanceof Map).toBeTruthy()590 })591 })feat: general typing improvements for TS 3.7 and upMichel Weststratebefore adoptionf930ce1
lines 592–605why, one step back592593 it("handles clear correctly", () => {594 const map = new Map([595 ["a", 1],596 ["c", 3]597 ])598 const next = produce(map, draft => {599 draft.delete("a")600 draft.set("b", 2)601 draft.set("c", 4)602 draft.clear()603 })604 expect(next).toEqual(new Map())605 })feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 606–609why, one step back606 })607608 describe("set drafts", () => {609 it("supports iteration", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 610–613why, one step back610 const base = new Set([611 {id: 1, a: 1},612 {id: 2, a: 1}613 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 614–626why, one step back614 const findById = (set, id) => {615 for (const item of set) {616 if (item.id === id) return item617 }618 return null619 }620 const result = produce(base, draft => {621 const obj1 = findById(draft, 1)622 const obj2 = findById(draft, 2)623 obj1.a = 2624 obj2.a = 2625 })626 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 627–638why, one step back627 expect(base).toEqual(628 new Set([629 {id: 1, a: 1},630 {id: 2, a: 1}631 ])632 )633 expect(result).toEqual(634 new Set([635 {id: 1, a: 2},636 {id: 2, a: 2}637 ])638 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 639–641why, one step back639 })640641 it("supports 'entries'", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 642–645why, one step back642 const base = new Set([643 {id: 1, a: 1},644 {id: 2, a: 1}645 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 646–659why, one step back646 const findById = (set, id) => {647 for (const [item1, item2] of set.entries()) {648 expect(item1).toBe(item2)649 if (item1.id === id) return item1650 }651 return null652 }653 const result = produce(base, draft => {654 const obj1 = findById(draft, 1)655 const obj2 = findById(draft, 2)656 obj1.a = 2657 obj2.a = 2658 })659 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 660–671why, one step back660 expect(base).toEqual(661 new Set([662 {id: 1, a: 1},663 {id: 2, a: 1}664 ])665 )666 expect(result).toEqual(667 new Set([668 {id: 1, a: 2},669 {id: 2, a: 2}670 ])671 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 672–674why, one step back672 })673674 it("supports 'values'", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 675–678why, one step back675 const base = new Set([676 {id: 1, a: 1},677 {id: 2, a: 1}678 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 679–691why, one step back679 const findById = (set, id) => {680 for (const item of set.values()) {681 if (item.id === id) return item682 }683 return null684 }685 const result = produce(base, draft => {686 const obj1 = findById(draft, 1)687 const obj2 = findById(draft, 2)688 obj1.a = 2689 obj2.a = 2690 })691 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 692–703why, one step back692 expect(base).toEqual(693 new Set([694 {id: 1, a: 1},695 {id: 2, a: 1}696 ])697 )698 expect(result).toEqual(699 new Set([700 {id: 1, a: 2},701 {id: 2, a: 2}702 ])703 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 704–706why, one step back704 })705706 it("supports 'keys'", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 707–710why, one step back707 const base = new Set([708 {id: 1, a: 1},709 {id: 2, a: 1}710 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 711–723why, one step back711 const findById = (set, id) => {712 for (const item of set.keys()) {713 if (item.id === id) return item714 }715 return null716 }717 const result = produce(base, draft => {718 const obj1 = findById(draft, 1)719 const obj2 = findById(draft, 2)720 obj1.a = 2721 obj2.a = 2722 })723 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 724–735why, one step back724 expect(base).toEqual(725 new Set([726 {id: 1, a: 1},727 {id: 2, a: 1}728 ])729 )730 expect(result).toEqual(731 new Set([732 {id: 1, a: 2},733 {id: 2, a: 2}734 ])735 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 736–738why, one step back736 })737738 it("supports forEach with mutation after reads", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 739–742why, one step back739 const base = new Set([740 {id: 1, a: 1},741 {id: 2, a: 2}742 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 743–756why, one step back743 const result = produce(base, draft => {744 let sum1 = 0745 draft.forEach(({a}) => {746 sum1 += a747 })748 expect(sum1).toBe(3)749 let sum2 = 0750 draft.forEach(item => {751 item.a += 10752 sum2 += item.a753 })754 expect(sum2).toBe(23)755 })756 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 757–768why, one step back757 expect(base).toEqual(758 new Set([759 {id: 1, a: 1},760 {id: 2, a: 2}761 ])762 )763 expect(result).toEqual(764 new Set([765 {id: 1, a: 11},766 {id: 2, a: 12}767 ])768 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 769–804why, one step back769 })770771 it("state stays the same if the same item is added", () => {772 const nextState = produce(baseState, s => {773 s.aSet.add("Luke")774 })775 expect(nextState).toBe(baseState)776 expect(nextState.aSet).toBe(baseState.aSet)777 })778779 it("can add new items", () => {780 const nextState = produce(baseState, s => {781 // Set.prototype.set should return the Set itself782 const res = s.aSet.add("force")783 expect(res).toBe(s.aSet[DRAFT_STATE].draft)784 })785 expect(nextState).not.toBe(baseState)786 expect(nextState.aSet).not.toBe(baseState.aSet)787 expect(baseState.aSet.has("force")).toBe(false)788 expect(nextState.aSet.has("force")).toBe(true)789 })790791 it("returns 'size'", () => {792 const nextState = produce(baseState, s => {793 s.aSet.add("newKey")794 expect(s.aSet.size).toBe(baseState.aSet.size + 1)795 })796 expect(nextState).not.toBe(baseState)797 expect(nextState.aSet).not.toBe(baseState.aSet)798 expect(nextState.aSet.has("newKey")).toBe(true)799 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)800 })801802 it("can use 'delete' to remove items", () => {803 const nextState = produce(baseState, s => {804 expect(s.aSet.has("Luke")).toBe(true)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 805–806why, one step back805 expect(s.aSet.delete("Luke")).toBe(true)806 expect(s.aSet.delete("Luke")).toBe(false)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 807–811why, one step back807 expect(s.aSet.has("Luke")).toBe(false)808 })809 expect(nextState.aSet).not.toBe(baseState.aSet)810 expect(baseState.aSet.has("Luke")).toBe(true)811 expect(nextState.aSet.has("Luke")).toBe(false)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 812why, one step back812 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 813–846why, one step back813 })814815 it("can use 'clear' to remove items", () => {816 const nextState = produce(baseState, s => {817 expect(s.aSet.size).not.toBe(0)818 s.aSet.clear()819 expect(s.aSet.size).toBe(0)820 })821 expect(nextState.aSet).not.toBe(baseState.aSet)822 expect(baseState.aSet.size).not.toBe(0)823 expect(nextState.aSet.size).toBe(0)824 })825826 it("supports 'has'", () => {827 const nextState = produce(baseState, s => {828 expect(s.aSet.has("newKey")).toBe(false)829 s.aSet.add("newKey")830 expect(s.aSet.has("newKey")).toBe(true)831 })832 expect(nextState).not.toBe(baseState)833 expect(nextState.aSet).not.toBe(baseState.aSet)834 expect(baseState.aSet.has("newKey")).toBe(false)835 expect(nextState.aSet.has("newKey")).toBe(true)836 })837838 it("supports nested sets", () => {839 const base = new Set([new Set(["Serenity"])])840 const result = produce(base, draft => {841 draft.forEach(nestedItem => nestedItem.add("Firefly"))842 })843 expect(result).not.toBe(base)844 expect(base).toEqual(new Set([new Set(["Serenity"])]))845 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))846 })feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 847–871why, one step back847848 it("supports has / delete on elements from the original", () => {849 const obj = {}850 const set = new Set([obj])851 const next = produce(set, d => {852 expect(d.has(obj)).toBe(true)853 d.add(3)854 expect(d.has(obj)).toBe(true)855 d.delete(obj)856 expect(d.has(obj)).toBe(false)857 })858 expect(next).toEqual(new Set([3]))859 })860861 it("revokes sets", () => {862 let m863 produce(baseState, s => {864 m = s.aSet865 })866 expect(() => m.has("x")).toThrow(867 "Cannot use a proxy that has been revoked"868 )869 expect(() => m.add("x")).toThrow(870 "Cannot use a proxy that has been revoked"871 )fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 872–878why, one step back872 })873874 it("does support instanceof Set", () => {875 const set = new Set()876 produce(set, d => {877 expect(d instanceof Set).toBeTruthy()878 })feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 879why, one step back879 })feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 880–881why, one step back880 })881style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 882–1405why, one step back882 it("supports `immerable` symbol on constructor", () => {883 class One {}884 One[immerable] = true885 const baseState = new One()886 const nextState = produce(baseState, draft => {887 expect(draft).not.toBe(baseState)888 draft.foo = true889 })890 expect(nextState).not.toBe(baseState)891 expect(nextState.foo).toBeTruthy()892 })893894 it("preserves symbol properties", () => {895 const test = Symbol("test")896 const baseState = {[test]: true}897 const nextState = produce(baseState, s => {898 expect(s[test]).toBeTruthy()899 s.foo = true900 })901 expect(nextState).toEqual({902 [test]: true,903 foo: true904 })905 })906907 it("preserves non-enumerable properties", () => {908 const baseState = {}909 // Non-enumerable object property910 Object.defineProperty(baseState, "foo", {911 value: {a: 1},912 enumerable: false913 })914 // Non-enumerable primitive property915 Object.defineProperty(baseState, "bar", {916 value: 1,917 enumerable: false918 })919 const nextState = produce(baseState, s => {920 expect(s.foo).toBeTruthy()921 expect(isEnumerable(s, "foo")).toBeFalsy()922 s.bar++923 expect(isEnumerable(s, "foo")).toBeFalsy()924 s.foo.a++925 expect(isEnumerable(s, "foo")).toBeFalsy()926 })927 expect(nextState.foo).toBeTruthy()928 expect(isEnumerable(nextState, "foo")).toBeFalsy()929 })930931 it("throws on computed properties", () => {932 const baseState = {}933 Object.defineProperty(baseState, "foo", {934 get: () => {},935 enumerable: true936 })937 expect(() => {938 produce(baseState, s => {939 // Proxies only throw once a change is made.940 if (useProxies) {941 s.modified = true942 }943 })944 }).toThrowErrorMatchingSnapshot()945 })946947 it("allows inherited computed properties", () => {948 const proto = {}949 Object.defineProperty(proto, "foo", {950 get() {951 return this.bar952 },953 set(val) {954 this.bar = val955 }956 })957 const baseState = Object.create(proto)958 produce(baseState, s => {959 expect(s.bar).toBeUndefined()960 s.foo = {}961 expect(s.bar).toBeDefined()962 expect(s.foo).toBe(s.bar)963 })964 })965966 it("supports a base state with multiple references to an object", () => {967 const obj = {}968 const res = produce({a: obj, b: obj}, d => {969 // Two drafts are created for each occurrence of an object in the base state.970 expect(d.a).not.toBe(d.b)971 d.a.z = true972 expect(d.b.z).toBeUndefined()973 })974 expect(res.b).toBe(obj)975 expect(res.a).not.toBe(res.b)976 expect(res.a.z).toBeTruthy()977 })978979 // NOTE: Except the root draft.980 it("supports multiple references to any modified draft", () => {981 const next = produce({a: {b: 1}}, d => {982 d.a.b++983 d.b = d.a984 })985 expect(next.a).toBe(next.b)986 })987988 it("can rename nested objects (no changes)", () => {989 const nextState = produce({obj: {}}, s => {990 s.foo = s.obj991 delete s.obj992 })993 expect(nextState).toEqual({foo: {}})994 })995996 // Very similar to the test before, but the reused object has one997 // property changed, one added, and one removed.998 it("can rename nested objects (with changes)", () => {999 const nextState = produce({obj: {a: 1, b: 1}}, s => {1000 s.obj.a = true // change1001 delete s.obj.b // delete1002 s.obj.c = true // add10031004 s.foo = s.obj1005 delete s.obj1006 })1007 expect(nextState).toEqual({foo: {a: true, c: true}})1008 })10091010 it("can nest a draft in a new object (no changes)", () => {1011 const baseState = {obj: {}}1012 const nextState = produce(baseState, s => {1013 s.foo = {bar: s.obj}1014 delete s.obj1015 })1016 expect(nextState.foo.bar).toBe(baseState.obj)1017 })10181019 it("can nest a modified draft in a new object", () => {1020 const nextState = produce({obj: {a: 1, b: 1}}, s => {1021 s.obj.a = true // change1022 delete s.obj.b // delete1023 s.obj.c = true // add10241025 s.foo = {bar: s.obj}1026 delete s.obj1027 })1028 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1029 })10301031 it("supports assigning undefined to an existing property", () => {1032 const nextState = produce(baseState, s => {1033 s.aProp = undefined1034 })1035 expect(nextState).not.toBe(baseState)1036 expect(nextState.aProp).toBe(undefined)1037 })10381039 it("supports assigning undefined to a new property", () => {1040 const baseState = {}1041 const nextState = produce(baseState, s => {1042 s.aProp = undefined1043 })1044 expect(nextState).not.toBe(baseState)1045 expect(nextState.aProp).toBe(undefined)1046 })10471048 // NOTE: ES5 drafts only protect existing properties when revoked.1049 it("revokes the draft once produce returns", () => {1050 const expectRevoked = (fn, shouldThrow = true) => {1051 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()1052 else expect(fn).not.toThrow()1053 }10541055 // Test object drafts:1056 let draft1057 produce({a: 1, b: 1}, s => {1058 draft = s1059 delete s.b1060 })10611062 // Access known property on object draft.1063 expectRevoked(() => {1064 draft.a1065 })10661067 // Assign known property on object draft.1068 expectRevoked(() => {1069 draft.a = true1070 })10711072 // Access unknown property on object draft.1073 expectRevoked(() => {1074 draft.z1075 }, useProxies)10761077 // Assign unknown property on object draft.1078 expectRevoked(() => {1079 draft.z = true1080 }, useProxies)10811082 // Test array drafts:1083 produce([1, 2], s => {1084 draft = s1085 s.pop()1086 })10871088 // Access known index of an array draft.1089 expectRevoked(() => {1090 draft[0]1091 })10921093 // Assign known index of an array draft.1094 expectRevoked(() => {1095 draft[0] = true1096 })10971098 // Access unknown index of an array draft.1099 expectRevoked(() => {1100 draft[1]1101 }, useProxies)11021103 // Assign unknown index of an array draft.1104 expectRevoked(() => {1105 draft[1] = true1106 }, useProxies)1107 })11081109 it("can access a child draft that was created before the draft was modified", () => {1110 produce({a: {}}, s => {1111 const before = s.a1112 s.b = 11113 expect(s.a).toBe(before)1114 })1115 })11161117 it("should reflect all changes made in the draft immediately", () => {1118 produce(baseState, draft => {1119 draft.anArray[0] = 51120 draft.anArray.unshift("test")1121 expect(enumerableOnly(draft.anArray)).toEqual(["test", 5, 2, {c: 3}, 1])1122 draft.stuffz = "coffee"1123 expect(draft.stuffz).toBe("coffee")1124 })1125 })11261127 if (useProxies)1128 it("throws when Object.defineProperty() is used on drafts", () => {1129 expect(() => {1130 produce({}, draft => {1131 Object.defineProperty(draft, "xx", {1132 enumerable: true,1133 writeable: true,1134 value: 21135 })1136 })1137 }).toThrowErrorMatchingSnapshot()1138 })11391140 it("should handle constructor correctly", () => {1141 const baseState = {1142 arr: new Array(),1143 obj: new Object()1144 }1145 const result = produce(baseState, draft => {1146 draft.arrConstructed = draft.arr.constructor(1)1147 draft.objConstructed = draft.obj.constructor(1)1148 })1149 expect(result.arrConstructed).toEqual(new Array().constructor(1))1150 expect(result.objConstructed).toEqual(new Object().constructor(1))1151 })11521153 it("should handle equality correctly - 1", () => {1154 const baseState = {1155 y: 3 / 0,1156 z: NaN1157 }1158 const nextState = produce(baseState, draft => {1159 draft.y = 4 / 01160 draft.z = NaN1161 })1162 expect(nextState).toBe(baseState)1163 })11641165 it("should handle equality correctly - 2", () => {1166 const baseState = {1167 x: -01168 }1169 const nextState = produce(baseState, draft => {1170 draft.x = +01171 })1172 expect(nextState).not.toBe(baseState)1173 expect(nextState).not.toEqual(baseState)1174 })11751176 // AKA: recursive produce calls1177 describe("nested producers", () => {1178 describe("when base state is not a draft", () => {1179 // This test ensures the global state used to manage proxies is1180 // never left in a corrupted state by a nested `produce` call.1181 it("never affects its parent producer implicitly", () => {1182 const base = {obj: {a: 1}}1183 const next = produce(base, draft => {1184 // Notice how `base.obj` is passed, not `draft.obj`1185 const obj2 = produce(base.obj, draft2 => {1186 draft2.a = 01187 })1188 expect(obj2.a).toBe(0)1189 expect(draft.obj.a).toBe(1) // effects should not be visible outside1190 })1191 expect(next).toBe(base)1192 })1193 })11941195 describe("when base state is a draft", () => {1196 it("always wraps the draft in a new draft", () => {1197 produce({}, parent => {1198 produce(parent, child => {1199 expect(child).not.toBe(parent)1200 expect(isDraft(child)).toBeTruthy()1201 expect(original(child)).toBe(parent)1202 })1203 })1204 })12051206 // Reported by: https://github.com/mweststrate/immer/issues/3431207 it("ensures each property is drafted", () => {1208 produce({a: {}, b: {}}, parent => {1209 parent.a // Access "a" but not "b"1210 produce(parent, child => {1211 child.c = 11212 expect(isDraft(child.a)).toBeTruthy()1213 expect(isDraft(child.b)).toBeTruthy()1214 })1215 })1216 })12171218 it("preserves any pending changes", () => {1219 produce({a: 1, b: 1, d: 1}, parent => {1220 parent.b = 21221 parent.c = 21222 delete parent.d1223 produce(parent, child => {1224 expect(child.a).toBe(1) // unchanged1225 expect(child.b).toBe(2) // changed1226 expect(child.c).toBe(2) // added1227 expect(child.d).toBeUndefined() // deleted1228 })1229 })1230 })1231 })12321233 describe("when base state contains a draft", () => {1234 it("wraps unowned draft with its own draft", () => {1235 produce({a: {}}, parent => {1236 produce({a: parent.a}, child => {1237 expect(child.a).not.toBe(parent.a)1238 expect(isDraft(child.a)).toBeTruthy()1239 expect(original(child.a)).toBe(parent.a)1240 })1241 })1242 })12431244 it("returns unowned draft if no changes were made", () => {1245 produce({a: {}}, parent => {1246 const result = produce({a: parent.a}, () => {})1247 expect(result.a).toBe(parent.a)1248 })1249 })12501251 it("clones the unowned draft when changes are made", () => {1252 produce({a: {}}, parent => {1253 const result = produce({a: parent.a}, child => {1254 child.a.b = 11255 })1256 expect(result.a).not.toBe(parent.a)1257 expect(result.a.b).toBe(1)1258 expect("b" in parent.a).toBeFalsy()1259 })1260 })12611262 // We cannot auto-freeze the result of a nested producer,1263 // because it may contain a draft from a parent producer.1264 it("never auto-freezes the result", () => {1265 produce({a: {}}, parent => {1266 const r = produce({a: parent.a}, child => {1267 child.b = 1 // Ensure a copy is returned.1268 })1269 expect(Object.isFrozen(r)).toBeFalsy()1270 })1271 })1272 })12731274 // "Upvalues" are variables from a parent scope.1275 it("does not finalize upvalue drafts", () => {1276 produce({a: {}, b: {}}, parent => {1277 expect(produce({}, () => parent)).toBe(parent)1278 parent.x // Ensure proxy not revoked.12791280 expect(produce({}, () => [parent])[0]).toBe(parent)1281 parent.x // Ensure proxy not revoked.12821283 expect(produce({}, () => parent.a)).toBe(parent.a)1284 parent.a.x // Ensure proxy not revoked.12851286 // Modified parent test1287 parent.c = 11288 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1289 parent.b.x // Ensure proxy not revoked.1290 })1291 })12921293 it("works with interweaved Immer instances", () => {1294 const options = {useProxies, autoFreeze}1295 const one = createPatchedImmer(options)1296 const two = createPatchedImmer(options)12971298 const base = {}1299 const result = one.produce(base, s1 =>1300 two.produce({s1}, s2 => {1301 expect(original(s2.s1)).toBe(s1)1302 s2.n = 11303 s2.s1 = one.produce({s2}, s3 => {1304 expect(original(s3.s2)).toBe(s2)1305 expect(original(s3.s2.s1)).toBe(s2.s1)1306 return s3.s2.s11307 })1308 })1309 )1310 expect(result.n).toBe(1)1311 expect(result.s1).toBe(base)1312 })1313 })13141315 if (useProxies)1316 it("throws when Object.setPrototypeOf() is used on a draft", () => {1317 produce({}, draft => {1318 expect(() =>1319 Object.setPrototypeOf(draft, Array)1320 ).toThrowErrorMatchingSnapshot()1321 })1322 })13231324 it("supports the 'in' operator", () => {1325 produce(baseState, draft => {1326 // Known property1327 expect("anArray" in draft).toBe(true)1328 expect(Reflect.has(draft, "anArray")).toBe(true)13291330 // Unknown property1331 expect("bla" in draft).toBe(false)1332 expect(Reflect.has(draft, "bla")).toBe(false)13331334 // Known index1335 expect(0 in draft.anArray).toBe(true)1336 expect("0" in draft.anArray).toBe(true)1337 expect(Reflect.has(draft.anArray, 0)).toBe(true)1338 expect(Reflect.has(draft.anArray, "0")).toBe(true)13391340 // Unknown index1341 expect(17 in draft.anArray).toBe(false)1342 expect("17" in draft.anArray).toBe(false)1343 expect(Reflect.has(draft.anArray, 17)).toBe(false)1344 expect(Reflect.has(draft.anArray, "17")).toBe(false)1345 })1346 })13471348 it("'this' should not be bound anymore - 1", () => {1349 const base = {x: 3}1350 const next1 = produce(base, function() {1351 expect(this).toBe(undefined)1352 })1353 })13541355 it("'this' should not be bound anymore - 2", () => {1356 const incrementor = produce(function() {1357 expect(this).toBe(undefined)1358 })1359 incrementor()1360 })13611362 it("should be possible to use dynamic bound this", () => {1363 const world = {1364 counter: {count: 1},1365 inc: produce(function(draft) {1366 expect(this).toBe(world)1367 draft.counter.count = this.counter.count + 11368 })1369 }13701371 expect(world.inc(world).counter.count).toBe(2)1372 })13731374 // See here: https://github.com/mweststrate/immer/issues/891375 it("supports the spread operator", () => {1376 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1377 const result = produce(base, draft => {1378 draft.foo = {x: 1, ...draft.foo, y: 1}1379 draft.bar = [1, ...draft.bar, 1]1380 })1381 expect(result).toEqual({1382 foo: {x: 0, y: 1},1383 bar: [1, 0, 0, 1]1384 })1385 })13861387 it("processes with lodash.set", () => {1388 const base = [{id: 1, a: 1}]1389 const result = produce(base, draft => {1390 lodash.set(draft, "[0].a", 2)1391 })1392 expect(base[0].a).toEqual(1)1393 expect(result[0].a).toEqual(2)1394 })13951396 it("processes with lodash.find", () => {1397 const base = [{id: 1, a: 1}]1398 const result = produce(base, draft => {1399 const obj1 = lodash.find(draft, {id: 1})1400 lodash.set(obj1, "a", 2)1401 })1402 expect(base[0].a).toEqual(1)1403 expect(result[0].a).toEqual(2)1404 })1405feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 1406–1419why, one step back1406 it("does not draft external data", () => {1407 const externalData = {x: 3}1408 const base = {}1409 const next = produce(base, draft => {1410 // potentially, we *could* draft external data automatically, but only if those statements are not switched...1411 draft.y = externalData1412 draft.y.x += 11413 externalData.x += 11414 })1415 expect(next).toEqual({y: {x: 5}})1416 expect(externalData.x).toBe(5)1417 expect(next.y).toBe(externalData)1418 })1419chore: added test for #491Michel Weststratebefore adoption788dc03
lines 1420–1434why, one step back1420 it("does not create new state unnecessary, #491", () => {1421 const a = {highlight: true}1422 const next1 = produce(a, draft => {1423 draft.highlight = false1424 draft.highlight = true1425 })1426 // See explanation in issue1427 expect(next1).not.toBe(a)14281429 const next2 = produce(a, draft => {1430 draft.highlight = true1431 })1432 expect(next2).toBe(a)1433 })1434test: tried to reproduce #469Michel Weststratebefore adoptione504e0b
line 1435why, one step back1435 autoFreeze &&chore: add test for #462Michel Weststratebefore adoptionce6a3c2
lines 1436–1453why, one step back1436 test.skip("issue #462 - frozen", () => {1437 var origin = {1438 a: {1439 value: "no"1440 },1441 b: {1442 value: "no"1443 }1444 }1445 var im = produce(origin, origin => {1446 origin.a.value = "im"1447 })1448 expect(() => (origin.b.value = "yes")).toThrow() // should throw!1449 // to prevent this...:1450 // expect(im.b.value).toBe('no');1451 })14521453 autoFreeze &&test: tried to reproduce #469Michel Weststratebefore adoptione504e0b
lines 1454–1471why, one step back1454 test("issue #469, state not frozen", () => {1455 const project = produce(1456 {1457 id: 1,1458 tracks: [{id: 1}]1459 },1460 () => {}1461 )14621463 expect(() => {1464 project.id = 2 // Does not throw error1465 }).toThrowError("Cannot assign to read only property 'id'")14661467 expect(() => {1468 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1469 }).toThrowError("Cannot assign to read only property 'id'")1470 })1471style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1472–1743why, one step back1472 describe("recipe functions", () => {1473 it("can return a new object", () => {1474 const base = {x: 3}1475 const res = produce(base, d => {1476 return {x: d.x + 1}1477 })1478 expect(res).not.toBe(base)1479 expect(res).toEqual({x: 4})1480 })14811482 it("can return the draft", () => {1483 const base = {x: 3}1484 const res = produce(base, d => {1485 d.x = 41486 return d1487 })1488 expect(res).not.toBe(base)1489 expect(res).toEqual({x: 4})1490 })14911492 it("can return an unmodified child draft", () => {1493 const base = {a: {}}1494 const res = produce(base, d => {1495 return d.a1496 })1497 expect(res).toBe(base.a)1498 })14991500 // TODO: Avoid throwing if only the child draft was modified.1501 it("cannot return a modified child draft", () => {1502 const base = {a: {}}1503 expect(() => {1504 produce(base, d => {1505 d.a.b = 11506 return d.a1507 })1508 }).toThrowErrorMatchingSnapshot()1509 })15101511 it("can return a frozen object", () => {1512 const res = deepFreeze([{x: 3}])1513 expect(produce({}, () => res)).toBe(res)1514 })15151516 it("can return an object with two references to another object", () => {1517 const next = produce({}, d => {1518 const obj = {}1519 return {obj, arr: [obj]}1520 })1521 expect(next.obj).toBe(next.arr[0])1522 })15231524 it("can return an object with two references to an unmodified draft", () => {1525 const base = {a: {}}1526 const next = produce(base, d => {1527 return [d.a, d.a]1528 })1529 expect(next[0]).toBe(base.a)1530 expect(next[0]).toBe(next[1])1531 })15321533 it("cannot return an object that references itself", () => {1534 const res = {}1535 res.self = res1536 expect(() => {1537 produce(res, () => res.self)1538 }).toThrowErrorMatchingSnapshot()1539 })1540 })15411542 describe("async recipe function", () => {1543 it("can modify the draft", () => {1544 const base = {a: 0, b: 0}1545 return produce(base, async d => {1546 d.a = 11547 await Promise.resolve()1548 d.b = 11549 }).then(res => {1550 expect(res).not.toBe(base)1551 expect(res).toEqual({a: 1, b: 1})1552 })1553 })15541555 it("works with rejected promises", () => {1556 let draft1557 const base = {a: 0, b: 0}1558 const err = new Error("passed")1559 return produce(base, d => {1560 draft = d1561 draft.b = 11562 return Promise.reject(err)1563 }).then(1564 () => {1565 throw "failed"1566 },1567 e => {1568 expect(e).toBe(err)1569 expect(() => draft.a).toThrowErrorMatchingSnapshot()1570 }1571 )1572 })15731574 it("supports recursive produce calls after await", () => {1575 const base = {obj: {k: 1}}1576 return produce(base, d => {1577 const obj = d.obj1578 delete d.obj1579 return Promise.resolve().then(() => {1580 d.a = produce({}, d => {1581 d.b = obj // Assign a draft owned by the parent scope.1582 })15831584 // Auto-freezing is prevented when an unowned draft exists.1585 expect(Object.isFrozen(d.a)).toBeFalsy()15861587 // Ensure `obj` is not revoked.1588 obj.c = 11589 })1590 }).then(res => {1591 expect(res).not.toBe(base)1592 expect(res).toEqual({1593 a: {b: {k: 1, c: 1}}1594 })1595 })1596 })1597 })15981599 it("throws when the draft is modified and another object is returned", () => {1600 const base = {x: 3}1601 expect(() => {1602 produce(base, draft => {1603 draft.x = 41604 return {x: 5}1605 })1606 }).toThrowErrorMatchingSnapshot()1607 })16081609 it("should fix #117 - 1", () => {1610 const reducer = (state, action) =>1611 produce(state, draft => {1612 switch (action.type) {1613 case "SET_STARTING_DOTS":1614 return draft.availableStartingDots.map(a => a)1615 default:1616 break1617 }1618 })1619 const base = {1620 availableStartingDots: [1621 {dots: 4, count: 1},1622 {dots: 3, count: 2},1623 {dots: 2, count: 3},1624 {dots: 1, count: 4}1625 ]1626 }1627 const next = reducer(base, {type: "SET_STARTING_DOTS"})1628 expect(next).toEqual(base.availableStartingDots)1629 expect(next).not.toBe(base.availableStartingDots)1630 })16311632 it("should fix #117 - 2", () => {1633 const reducer = (state, action) =>1634 produce(state, draft => {1635 switch (action.type) {1636 case "SET_STARTING_DOTS":1637 return {1638 dots: draft.availableStartingDots.map(a => a)1639 }1640 default:1641 break1642 }1643 })1644 const base = {1645 availableStartingDots: [1646 {dots: 4, count: 1},1647 {dots: 3, count: 2},1648 {dots: 2, count: 3},1649 {dots: 1, count: 4}1650 ]1651 }1652 const next = reducer(base, {type: "SET_STARTING_DOTS"})1653 expect(next).toEqual({dots: base.availableStartingDots})1654 })16551656 it("cannot always detect noop assignments - 0", () => {1657 const baseState = {x: {y: 3}}1658 const nextState = produce(baseState, d => {1659 const a = d.x1660 d.x = a1661 })1662 expect(nextState).toBe(baseState)1663 })16641665 it("cannot always detect noop assignments - 1", () => {1666 const baseState = {x: {y: 3}}1667 const nextState = produce(baseState, d => {1668 const a = d.x1669 d.x = 41670 d.x = a1671 })1672 // Ideally, this should actually be the same instances1673 // but this would be pretty expensive to detect,1674 // so we don't atm1675 expect(nextState).not.toBe(baseState)1676 })16771678 it("cannot always detect noop assignments - 2", () => {1679 const baseState = {x: {y: 3}}1680 const nextState = produce(baseState, d => {1681 const a = d.x1682 const stuff = a.y + 31683 d.x = 41684 d.x = a1685 })1686 // Ideally, this should actually be the same instances1687 // but this would be pretty expensive to detect,1688 // so we don't atm1689 expect(nextState).not.toBe(baseState)1690 })16911692 it("cannot always detect noop assignments - 3", () => {1693 const baseState = {x: 3}1694 const nextState = produce(baseState, d => {1695 d.x = 31696 })1697 expect(nextState).toBe(baseState)1698 })16991700 it("cannot always detect noop assignments - 4", () => {1701 const baseState = {x: 3}1702 const nextState = produce(baseState, d => {1703 d.x = 41704 d.x = 31705 })1706 // Ideally, this should actually be the same instances1707 // but this would be pretty expensive to detect,1708 // so we don't atm1709 expect(nextState).not.toBe(baseState)1710 })17111712 it("cannot produce undefined by returning undefined", () => {1713 const base = 31714 expect(produce(base, () => 4)).toBe(4)1715 expect(produce(base, () => null)).toBe(null)1716 expect(produce(base, () => undefined)).toBe(3)1717 expect(produce(base, () => {})).toBe(3)1718 expect(produce(base, () => nothing)).toBe(undefined)17191720 expect(produce({}, () => undefined)).toEqual({})1721 expect(produce({}, () => nothing)).toBe(undefined)1722 expect(produce(3, () => nothing)).toBe(undefined)17231724 expect(produce(() => undefined)({})).toEqual({})1725 expect(produce(() => nothing)({})).toBe(undefined)1726 expect(produce(() => nothing)(3)).toBe(undefined)1727 })17281729 describe("base state type", () => {1730 testObjectTypes(produce)1731 testLiteralTypes(produce)1732 })17331734 afterEach(() => {1735 expect(baseState).toBe(origBaseState)1736 expect(baseState).toEqual(createBaseState())1737 })17381739 class Foo {}1740 function createBaseState() {1741 const data = {1742 anInstance: new Foo(),1743 anArray: [3, 2, {c: 3}, 1],feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1744–1755why, one step back1744 aMap: new Map([1745 ["jedi", {name: "Luke", skill: 10}],1746 ["jediTotal", 42],1747 ["force", "these aren't the droids you're looking for"]1748 ]),1749 aSet: new Set([1750 "Luke",1751 42,1752 {1753 jedi: "Yoda"1754 }1755 ]),style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1756–1805why, one step back1756 aProp: "hi",1757 anObject: {1758 nested: {1759 yummie: true1760 },1761 coffee: false1762 }1763 }1764 return autoFreeze ? deepFreeze(data) : data1765 }1766 })17671768 describe(`isDraft - ${name}`, () => {1769 it("returns true for object drafts", () => {1770 produce({}, state => {1771 expect(isDraft(state)).toBeTruthy()1772 })1773 })1774 it("returns true for array drafts", () => {1775 produce([], state => {1776 expect(isDraft(state)).toBeTruthy()1777 })1778 })1779 it("returns true for objects nested in object drafts", () => {1780 produce({a: {b: {}}}, state => {1781 expect(isDraft(state.a)).toBeTruthy()1782 expect(isDraft(state.a.b)).toBeTruthy()1783 })1784 })1785 it("returns false for new objects added to a draft", () => {1786 produce({}, state => {1787 state.a = {}1788 expect(isDraft(state.a)).toBeFalsy()1789 })1790 })1791 it("returns false for objects returned by the producer", () => {1792 const object = produce(null, Object.create)1793 expect(isDraft(object)).toBeFalsy()1794 })1795 it("returns false for arrays returned by the producer", () => {1796 const array = produce(null, _ => [])1797 expect(isDraft(array)).toBeFalsy()1798 })1799 it("returns false for object drafts returned by the producer", () => {1800 const object = produce({}, state => state)1801 expect(isDraft(object)).toBeFalsy()1802 })1803 it("returns false for array drafts returned by the producer", () => {1804 const array = produce([], state => state)1805 expect(isDraft(array)).toBeFalsy()feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1806–1814why, one step back1806 })1807 })18081809 describe(`complex nesting map / set / object`, () => {1810 const a = {a: 1}1811 const b = {b: 2}1812 const c = {c: 3}1813 const set1 = new Set([a, b])1814 const set2 = new Set([c])feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 1815–1818why, one step back1815 const map = new Map([1816 ["set1", set1],1817 ["set2", set2]1818 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1819–1867why, one step back1819 const base = {map}18201821 function first(set) {1822 return Array.from(set.values())[0]1823 }18241825 function second(set) {1826 return Array.from(set.values())[1]1827 }18281829 test(`modify deep object`, () => {1830 const [res, patches] = produceWithPatches(base, draft => {1831 const v = first(draft.map.get("set1"))1832 expect(original(v)).toBe(a)1833 expect(v).toEqual(a)1834 expect(v).not.toBe(a)1835 v.a++1836 })1837 expect(res).toMatchSnapshot()1838 expect(patches).toMatchSnapshot()1839 expect(a.a).toBe(1)1840 expect(base.map.get("set1")).toBe(set1)1841 expect(first(base.map.get("set1"))).toBe(a)1842 expect(res).not.toBe(base)1843 expect(res.map).not.toBe(base.map)1844 expect(res.map.get("set1")).not.toBe(base.map.get("set1"))1845 expect(second(base.map.get("set1"))).toBe(b)1846 expect(base.map.get("set2")).toBe(set2)1847 expect(first(res.map.get("set1"))).toEqual({a: 2})1848 })18491850 test(`modify deep object - keep value`, () => {1851 const [res, patches] = produceWithPatches(base, draft => {1852 const v = first(draft.map.get("set1"))1853 expect(original(v)).toBe(a)1854 expect(v).toEqual(a)1855 expect(v).not.toBe(a)1856 v.a = 1 // same value1857 })1858 expect(a.a).toBe(1)1859 expect(base.map.get("set1")).toBe(set1)1860 expect(first(base.map.get("set1"))).toBe(a)1861 expect(res).toBe(base)1862 expect(res.map).toBe(base.map)1863 expect(res.map.get("set1")).toBe(base.map.get("set1"))1864 expect(first(res.map.get("set1"))).toBe(a)1865 expect(second(base.map.get("set1"))).toBe(b)1866 expect(base.map.get("set2")).toBe(set2)1867 expect(patches.length).toBe(0)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1868–1871why, one step back1868 })1869 })1870}1871chore: improve more testsaleclarsonbefore adoption4f59b12
line 1872why, one step back1872function testObjectTypes(produce) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1873–1925why, one step back1873 class Foo {1874 constructor(foo) {1875 this.foo = foo1876 this[immerable] = true1877 }1878 }1879 const values = {1880 "empty object": {},1881 "plain object": {a: 1, b: 2},1882 "object (no prototype)": Object.create(null),1883 "empty array": [],1884 "plain array": [1, 2],1885 "class instance (draftable)": new Foo(1)1886 }1887 for (const name in values) {1888 const value = values[name]1889 const copy = shallowCopy(value)1890 testObjectType(name, value)1891 testObjectType(name + " (frozen)", Object.freeze(copy))1892 }1893 function testObjectType(name, base) {1894 describe(name, () => {1895 it("creates a draft", () => {1896 produce(base, draft => {1897 expect(draft).not.toBe(base)1898 expect(shallowCopy(draft, true)).toEqual(base)1899 })1900 })19011902 it("preserves the prototype", () => {1903 const proto = Object.getPrototypeOf(base)1904 produce(base, draft => {1905 expect(Object.getPrototypeOf(draft)).toBe(proto)1906 })1907 })19081909 it("returns the base state when no changes are made", () => {1910 expect(produce(base, () => {})).toBe(base)1911 })19121913 it("returns a copy when changes are made", () => {1914 const random = Math.random()1915 const result = produce(base, draft => {1916 draft[0] = random1917 })1918 expect(result).not.toBe(base)1919 expect(result.constructor).toBe(base.constructor)1920 expect(result[0]).toBe(random)1921 })1922 })1923 }1924}1925chore: improve more testsaleclarsonbefore adoption4f59b12
line 1926why, one step back1926function testLiteralTypes(produce) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1927–1979why, one step back1927 class Foo {}1928 const values = {1929 "falsy number": 0,1930 "truthy number": 1,1931 "negative number": -1,1932 NaN: NaN,1933 infinity: 1 / 0,1934 true: true,1935 false: false,1936 "empty string": "",1937 "truthy string": "1",1938 null: null,1939 undefined: undefined,19401941 /**1942 * These objects are treated as literals because Immer1943 * does not know how to draft them.1944 */1945 function: () => {},1946 "regexp object": /.+/g,1947 "boxed number": new Number(0),1948 "boxed string": new String(""),1949 "boxed boolean": new Boolean(),1950 "date object": new Date(),1951 "class instance (not draftable)": new Foo()1952 }1953 for (const name in values) {1954 describe(name, () => {1955 const value = values[name]19561957 it("does not create a draft", () => {1958 produce(value, draft => {1959 expect(draft).toBe(value)1960 })1961 })19621963 it("returns the base state when no changes are made", () => {1964 expect(produce(value, () => {})).toBe(value)1965 })19661967 if (value && typeof value == "object") {1968 it("does not return a copy when changes are made", () => {1969 expect(1970 produce(value, draft => {1971 draft.foo = true1972 })1973 ).toBe(value)1974 })1975 }1976 })1977 }1978}1979test: rename test.tsconfig.json so vscode can find italeclarsonbefore adoption721c488
line 1980why, one step back1980function enumerableOnly(x) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1981–1987why, one step back1981 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1982 each(copy, (prop, value) => {1983 if (value && typeof value === "object") {1984 copy[prop] = enumerableOnly(value)1985 }1986 })1987 return copytest: rename test.tsconfig.json so vscode can find italeclarsonbefore adoption721c488
line 1988why, one step back1988}