base.js
This file
Path
__tests__/base.js
2,162 lines · 55.4 KiB · JavaScript
Last changed by
Errors for prodMichel Weststratebefore adoption67565dd
History of this fileTake it
The walk stopped after 200 commits: lines older than 21846ab point at it.
test: extract some tests into their own functionaleclarsonbefore adoption21846ab
line 1why, one step back1"use strict"New build set. Current statsMichel Weststratebefore adoption9aec0fe
lines 2–9why, one step back2import {3 Immer,4 nothing,5 original,6 isDraft,7 immerable,8 enableAllPlugins9} from "../src/immer"Optimization: stop recursing if there are no drafts leftMichel Weststratebefore adoptionebda6f8
line 10why, one step back10import {each, shallowCopy, DRAFT_STATE} from "../src/internal"test: extract some tests into their own functionaleclarsonbefore adoption21846ab
lines 11–15why, one step back11import deepFreeze from "deep-freeze"12import cloneDeep from "lodash.clonedeep"13import * as lodash from "lodash"1415jest.setTimeout(1000)New build set. Current statsMichel Weststratebefore adoption9aec0fe
lines 16–17why, one step back1617enableAllPlugins()test: extract some tests into their own functionaleclarsonbefore adoption21846ab
line 18why, one step back18chore: improve more testsaleclarsonbefore adoption4f59b12
line 19why, one step back19test("immer should have no dependencies", () => {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 20why, one step back20 expect(require("../package.json").dependencies).toBeUndefined()chore: improve more testsaleclarsonbefore adoption4f59b12
line 21why, one step back21})style: use tabsuse-tabsbefore adoptiona9c0fd0
line 22why, one step back22test: extract some tests into their own functionaleclarsonbefore adoption21846ab
lines 23–24why, one step back23runBaseTest("proxy (no freeze)", true, false)24runBaseTest("proxy (autofreeze)", true, true)added base tests for autofreeze + patch listenersMichel Weststratebefore adoption9f07525
line 25why, one step back25runBaseTest("proxy (patch listener)", true, false, true)test: extract some tests into their own functionaleclarsonbefore adoption21846ab
line 26why, one step back26runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)Initial finalize cleanupMichel Weststratebefore adoption67ab3ab
line 27why, one step back27test: extract some tests into their own functionaleclarsonbefore adoption21846ab
lines 28–29why, one step back28runBaseTest("es5 (no freeze)", false, false)29runBaseTest("es5 (autofreeze)", false, true)added base tests for autofreeze + patch listenersMichel Weststratebefore adoption9f07525
line 30why, one step back30runBaseTest("es5 (patch listener)", false, false, true)test: extract some tests into their own functionaleclarsonbefore adoption21846ab
line 31why, one step back31runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)style: use tabsuse-tabsbefore adoptiona9c0fd0
line 32why, one step back32test: extract some tests into their own functionaleclarsonbefore adoption21846ab
line 33why, one step back33function runBaseTest(name, useProxies, autoFreeze, useListener) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 34why, one step back34 const listener = useListener ? function() {} : undefinedfeat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 35why, one step back35 const {produce, produceWithPatches} = createPatchedImmer({style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 36–45why, one step back36 useProxies,37 autoFreeze38 })3940 // When `useListener` is true, append a function to the arguments of every41 // uncurried `produce` call in every test. This makes tests easier to read.42 function createPatchedImmer(options) {43 const immer = new Immer(options)4445 const {produce} = immerfeat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 46–47why, one step back46 immer.produce = function(...args) {47 return typeof args[1] === "function" && args.length < 3style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 48–49why, one step back48 ? produce(...args, listener)49 : produce(...args)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 50why, one step back50 }style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 51–202why, one step back5152 return immer53 }5455 describe(`base functionality - ${name}`, () => {56 let baseState57 let origBaseState5859 beforeEach(() => {60 origBaseState = baseState = createBaseState()61 })6263 it("returns the original state when no changes are made", () => {64 const nextState = produce(baseState, s => {65 expect(s.aProp).toBe("hi")66 expect(s.anObject.nested).toMatchObject({yummie: true})67 })68 expect(nextState).toBe(baseState)69 })7071 it("does structural sharing", () => {72 const random = Math.random()73 const nextState = produce(baseState, s => {74 s.aProp = random75 })76 expect(nextState).not.toBe(baseState)77 expect(nextState.aProp).toBe(random)78 expect(nextState.nested).toBe(baseState.nested)79 })8081 it("deep change bubbles up", () => {82 const nextState = produce(baseState, s => {83 s.anObject.nested.yummie = false84 })85 expect(nextState).not.toBe(baseState)86 expect(nextState.anObject).not.toBe(baseState.anObject)87 expect(baseState.anObject.nested.yummie).toBe(true)88 expect(nextState.anObject.nested.yummie).toBe(false)89 expect(nextState.anArray).toBe(baseState.anArray)90 })9192 it("can add props", () => {93 const nextState = produce(baseState, s => {94 s.anObject.cookie = {tasty: true}95 })96 expect(nextState).not.toBe(baseState)97 expect(nextState.anObject).not.toBe(baseState.anObject)98 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)99 expect(nextState.anObject.cookie).toEqual({tasty: true})100 })101102 it("can delete props", () => {103 const nextState = produce(baseState, s => {104 delete s.anObject.nested105 })106 expect(nextState).not.toBe(baseState)107 expect(nextState.anObject).not.toBe(baseState.anObject)108 expect(nextState.anObject.nested).toBe(undefined)109 })110111 // Found by: https://github.com/mweststrate/immer/pull/267112 it("can delete props added in the producer", () => {113 const nextState = produce(baseState, s => {114 s.anObject.test = true115 delete s.anObject.test116 })117 if (useProxies) {118 expect(nextState).not.toBe(baseState)119 expect(nextState).toEqual(baseState)120 } else {121 // The copy is avoided in ES5.122 expect(nextState).toBe(baseState)123 }124 })125126 // Found by: https://github.com/mweststrate/immer/issues/328127 it("can set a property that was just deleted", () => {128 const baseState = {a: 1}129 const nextState = produce(baseState, s => {130 delete s.a131 s.a = 2132 })133 expect(nextState.a).toBe(2)134 })135136 it("can set a property to its original value after deleting it", () => {137 const baseState = {a: {b: 1}}138 const nextState = produce(baseState, s => {139 const a = s.a140 delete s.a141 s.a = a142 })143 if (useProxies) {144 expect(nextState).not.toBe(baseState)145 expect(nextState).toEqual(baseState)146 } else {147 // The copy is avoided in ES5.148 expect(nextState).toBe(baseState)149 }150 })151152 it("can get property descriptors", () => {153 const getDescriptor = Object.getOwnPropertyDescriptor154 const baseState = deepFreeze([{a: 1}])155 produce(baseState, arr => {156 const obj = arr[0]157 const desc = {158 configurable: true,159 enumerable: true,160 ...(useProxies && {writable: true})161 }162163 // Known property164 expect(getDescriptor(obj, "a")).toMatchObject(desc)165 expect(getDescriptor(arr, 0)).toMatchObject(desc)166167 // Deleted property168 delete obj.a169 arr.pop()170 expect(getDescriptor(obj, "a")).toBeUndefined()171 expect(getDescriptor(arr, 0)).toBeUndefined()172173 // Unknown property174 expect(getDescriptor(obj, "b")).toBeUndefined()175 expect(getDescriptor(arr, 100)).toBeUndefined()176177 // Added property178 obj.b = 2179 arr[100] = 1180 expect(getDescriptor(obj, "b")).toBeDefined()181 expect(getDescriptor(arr, 100)).toBeDefined()182 })183 })184185 describe("array drafts", () => {186 it("supports Array.isArray()", () => {187 const nextState = produce(baseState, s => {188 expect(Array.isArray(s.anArray)).toBeTruthy()189 s.anArray.push(1)190 })191 expect(Array.isArray(nextState.anArray)).toBeTruthy()192 })193194 it("supports index access", () => {195 const value = baseState.anArray[0]196 const nextState = produce(baseState, s => {197 expect(s.anArray[0]).toBe(value)198 })199 expect(nextState).toBe(baseState)200 })201202 it("supports iteration", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 203–206why, one step back203 const base = [204 {id: 1, a: 1},205 {id: 2, a: 1}206 ]style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 207–296why, one step back207 const findById = (collection, id) => {208 for (const item of collection) {209 if (item.id === id) return item210 }211 return null212 }213 const result = produce(base, draft => {214 const obj1 = findById(draft, 1)215 const obj2 = findById(draft, 2)216 obj1.a = 2217 obj2.a = 2218 })219 expect(result[0].a).toEqual(2)220 expect(result[1].a).toEqual(2)221 })222223 it("can assign an index via bracket notation", () => {224 const nextState = produce(baseState, s => {225 s.anArray[3] = true226 })227 expect(nextState).not.toBe(baseState)228 expect(nextState.anArray).not.toBe(baseState.anArray)229 expect(nextState.anArray[3]).toEqual(true)230 })231232 it("can use splice() to both add and remove items", () => {233 const nextState = produce(baseState, s => {234 s.anArray.splice(1, 1, "a", "b")235 })236 expect(nextState.anArray).not.toBe(baseState.anArray)237 expect(nextState.anArray[1]).toBe("a")238 expect(nextState.anArray[2]).toBe("b")239 })240241 it("can truncate via the length property", () => {242 const baseLength = baseState.anArray.length243 const nextState = produce(baseState, s => {244 s.anArray.length = baseLength - 1245 })246 expect(nextState.anArray).not.toBe(baseState.anArray)247 expect(nextState.anArray.length).toBe(baseLength - 1)248 })249250 it("can extend via the length property", () => {251 const baseLength = baseState.anArray.length252 const nextState = produce(baseState, s => {253 s.anArray.length = baseLength + 1254 })255 expect(nextState.anArray).not.toBe(baseState.anArray)256 expect(nextState.anArray.length).toBe(baseLength + 1)257 })258259 // Reported here: https://github.com/mweststrate/immer/issues/116260 it("can pop then push", () => {261 const nextState = produce([1, 2, 3], s => {262 s.pop()263 s.push(100)264 })265 expect(nextState).toEqual([1, 2, 100])266 })267268 it("can be sorted", () => {269 const baseState = [3, 1, 2]270 const nextState = produce(baseState, s => {271 s.sort()272 })273 expect(nextState).not.toBe(baseState)274 expect(nextState).toEqual([1, 2, 3])275 })276277 it("supports modifying nested objects", () => {278 const baseState = [{a: 1}, {}]279 const nextState = produce(baseState, s => {280 s[0].a++281 s[1].a = 0282 })283 expect(nextState).not.toBe(baseState)284 expect(nextState[0].a).toBe(2)285 expect(nextState[1].a).toBe(0)286 })287288 it("never preserves non-numeric properties", () => {289 const baseState = []290 baseState.x = 7291 const nextState = produce(baseState, s => {292 s.push(3)293 })294 expect("x" in nextState).toBeFalsy()295 })296Errors for prodMichel Weststratebefore adoption67565dd
line 297why, one step back297 if (useProxies && !global.USES_BUILD) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 298–317why, one step back298 it("throws when a non-numeric property is added", () => {299 expect(() => {300 produce([], d => {301 d.x = 3302 })303 }).toThrowErrorMatchingSnapshot()304 })305306 it("throws when a non-numeric property is deleted", () => {307 expect(() => {308 const baseState = []309 baseState.x = 7310 produce(baseState, d => {311 delete d.x312 })313 }).toThrowErrorMatchingSnapshot()314 })315 }316 })317feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 318–403why, one step back318 describe("map drafts", () => {319 it("supports key access", () => {320 const value = baseState.aMap.get("jedi")321 const nextState = produce(baseState, s => {322 expect(s.aMap.get("jedi")).toEqual(value)323 })324 expect(nextState).toBe(baseState)325 })326327 it("supports key access for non-primitive keys", () => {328 const key = {prop: "val"}329 const base = new Map([[key, {id: 1, a: 1}]])330 const value = base.get(key)331 const nextState = produce(base, s => {332 expect(s.get(key)).toEqual(value)333 })334 expect(nextState).toBe(base)335 })336337 it("supports iteration", () => {338 const base = new Map([339 ["first", {id: 1, a: 1}],340 ["second", {id: 2, a: 1}]341 ])342 const findById = (map, id) => {343 for (const [, item] of map) {344 if (item.id === id) return item345 }346 return null347 }348 const result = produce(base, draft => {349 const obj1 = findById(draft, 1)350 const obj2 = findById(draft, 2)351 obj1.a = 2352 obj2.a = 2353 })354 expect(result).not.toBe(base)355 expect(result.get("first").a).toEqual(2)356 expect(result.get("second").a).toEqual(2)357 })358359 it("supports 'entries'", () => {360 const base = new Map([361 ["first", {id: 1, a: 1}],362 ["second", {id: 2, a: 1}]363 ])364 const findById = (map, id) => {365 for (const [, item] of map.entries()) {366 if (item.id === id) return item367 }368 return null369 }370 const result = produce(base, draft => {371 const obj1 = findById(draft, 1)372 const obj2 = findById(draft, 2)373 obj1.a = 2374 obj2.a = 2375 })376 expect(result).not.toBe(base)377 expect(result.get("first").a).toEqual(2)378 expect(result.get("second").a).toEqual(2)379 })380381 it("supports 'values'", () => {382 const base = new Map([383 ["first", {id: 1, a: 1}],384 ["second", {id: 2, a: 1}]385 ])386 const findById = (map, id) => {387 for (const item of map.values()) {388 if (item.id === id) return item389 }390 return null391 }392 const result = produce(base, draft => {393 const obj1 = findById(draft, 1)394 const obj2 = findById(draft, 2)395 obj1.a = 2396 obj2.a = 2397 })398 expect(result).not.toBe(base)399 expect(result.get("first").a).toEqual(2)400 expect(result.get("second").a).toEqual(2)401 })402403 it("supports 'keys", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 404–407why, one step back404 const base = new Map([405 ["first", Symbol()],406 ["second", Symbol()]407 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 408–469why, one step back408 const result = produce(base, draft => {409 expect([...draft.keys()]).toEqual(["first", "second"])410 draft.set("third", Symbol())411 expect([...draft.keys()]).toEqual(["first", "second", "third"])412 })413 })414415 it("supports forEach", () => {416 const key1 = {prop: "val1"}417 const key2 = {prop: "val2"}418 const base = new Map([419 ["first", {id: 1, a: 1}],420 ["second", {id: 2, a: 1}],421 [key1, {id: 3, a: 1}],422 [key2, {id: 4, a: 1}]423 ])424 const result = produce(base, draft => {425 let sum1 = 0426 draft.forEach(({a}) => {427 sum1 += a428 })429 expect(sum1).toBe(4)430 let sum2 = 0431 draft.get("first").a = 10432 draft.get("second").a = 20433 draft.get(key1).a = 30434 draft.get(key2).a = 40435 draft.forEach(({a}) => {436 sum2 += a437 })438 expect(sum2).toBe(100)439 })440 expect(result).not.toBe(base)441 expect(base.get("first").a).toEqual(1)442 expect(base.get("second").a).toEqual(1)443 expect(base.get(key1).a).toEqual(1)444 expect(base.get(key2).a).toEqual(1)445 expect(result.get("first").a).toEqual(10)446 expect(result.get("second").a).toEqual(20)447 expect(result.get(key1).a).toEqual(30)448 expect(result.get(key2).a).toEqual(40)449 })450451 it("supports forEach mutation", () => {452 const base = new Map([453 ["first", {id: 1, a: 1}],454 ["second", {id: 2, a: 1}]455 ])456 const result = produce(base, draft => {457 draft.forEach(item => {458 item.a = 100459 })460 })461 expect(result).not.toBe(base)462 expect(result.get("first").a).toEqual(100)463 expect(result.get("second").a).toEqual(100)464 })465466 it("can assign by key", () => {467 const nextState = produce(baseState, s => {468 // Map.prototype.set should return the Map itself469 const res = s.aMap.set("force", true)Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
line 470why, one step back470 if (!global.USES_BUILD) expect(res).toBe(s.aMap[DRAFT_STATE].draft_)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 471–510why, one step back471 })472 expect(nextState).not.toBe(baseState)473 expect(nextState.aMap).not.toBe(baseState.aMap)474 expect(nextState.aMap.get("force")).toEqual(true)475 })476477 it("can assign by a non-primitive key", () => {478 const key = {prop: "val"}479 const value = {id: 1, a: 1}480 const base = new Map([[key, value]])481 const nextState = produce(base, s => {482 s.set(key, true)483 })484 expect(nextState).not.toBe(base)485 expect(base.get(key)).toEqual(value)486 expect(nextState.get(key)).toEqual(true)487 })488489 it("state stays the same if the the same item is assigned by key", () => {490 const nextState = produce(baseState, s => {491 s.aMap.set("jediTotal", 42)492 })493 expect(nextState).toBe(baseState)494 expect(nextState.aMap).toBe(baseState.aMap)495 })496497 it("returns 'size'", () => {498 const nextState = produce(baseState, s => {499 s.aMap.set("newKey", true)500 expect(s.aMap.size).toBe(baseState.aMap.size + 1)501 })502 expect(nextState).not.toBe(baseState)503 expect(nextState.aMap).not.toBe(baseState.aMap)504 expect(nextState.aMap.get("newKey")).toEqual(true)505 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)506 })507508 it("can use 'delete' to remove items", () => {509 const nextState = produce(baseState, s => {510 expect(s.aMap.has("jedi")).toBe(true)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 511why, one step back511 expect(s.aMap.delete("jedi")).toBe(true)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 512–555why, one step back512 expect(s.aMap.has("jedi")).toBe(false)513 })514 expect(nextState.aMap).not.toBe(baseState.aMap)515 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)516 expect(baseState.aMap.has("jedi")).toBe(true)517 expect(nextState.aMap.has("jedi")).toBe(false)518 })519520 it("can use 'clear' to remove items", () => {521 const nextState = produce(baseState, s => {522 expect(s.aMap.size).not.toBe(0)523 s.aMap.clear()524 expect(s.aMap.size).toBe(0)525 })526 expect(nextState.aMap).not.toBe(baseState.aMap)527 expect(baseState.aMap.size).not.toBe(0)528 expect(nextState.aMap.size).toBe(0)529 })530531 it("support 'has'", () => {532 const nextState = produce(baseState, s => {533 expect(s.aMap.has("newKey")).toBe(false)534 s.aMap.set("newKey", true)535 expect(s.aMap.has("newKey")).toBe(true)536 })537 expect(nextState).not.toBe(baseState)538 expect(nextState.aMap).not.toBe(baseState.aMap)539 expect(baseState.aMap.has("newKey")).toBe(false)540 expect(nextState.aMap.has("newKey")).toBe(true)541 })542543 it("supports nested maps", () => {544 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])545 const result = produce(base, draft => {546 draft.get("first").get("second").prop = "test1"547 })548 expect(result).not.toBe(base)549 expect(result.get("first")).not.toBe(base.get("first"))550 expect(result.get("first").get("second")).not.toBe(551 base.get("first").get("second")552 )553 expect(base.get("first").get("second").prop).toBe("test")554 expect(result.get("first").get("second").prop).toBe("test1")555 })feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 556–569why, one step back556557 it("treats void deletes as no-op", () => {558 const base = new Map([["x", 1]])559 const next = produce(base, d => {560 expect(d.delete("y")).toBe(false)561 })562 expect(next).toBe(base)563 })564565 it("revokes map proxies", () => {566 let m567 produce(baseState, s => {568 m = s.aMap569 })Errors for prodMichel Weststratebefore adoption67565dd
lines 570–571why, one step back570 expect(() => m.get("x")).toThrowErrorMatchingSnapshot()571 expect(() => m.set("x", 3)).toThrowErrorMatchingSnapshot()feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 572–592why, one step back572 })573574 it("does not draft map keys", () => {575 // anything else would be terribly confusing576 const key = {a: 1}577 const map = new Map([[key, 2]])578 const next = produce(map, d => {579 const dKey = Array.from(d.keys())[0]580 expect(isDraft(dKey)).toBe(false)581 expect(dKey).toBe(key)582 dKey.a += 1583 d.set(dKey, d.get(dKey) + 1)584 d.set(key, d.get(key) + 1)585 expect(d.get(key)).toBe(4)586 expect(key.a).toBe(2)587 })588 const entries = Array.from(next.entries())589 expect(entries).toEqual([[key, 4]])590 expect(entries[0][0]).toBe(key)591 expect(entries[0][0].a).toBe(2)592 })fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 593–599why, one step back593594 it("does support instanceof Map", () => {595 const map = new Map()596 produce(map, d => {597 expect(d instanceof Map).toBeTruthy()598 })599 })feat: general typing improvements for TS 3.7 and upMichel Weststratebefore adoptionf930ce1
lines 600–613why, one step back600601 it("handles clear correctly", () => {602 const map = new Map([603 ["a", 1],604 ["c", 3]605 ])606 const next = produce(map, draft => {607 draft.delete("a")608 draft.set("b", 2)609 draft.set("c", 4)610 draft.clear()611 })612 expect(next).toEqual(new Map())613 })feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 614–617why, one step back614 })615616 describe("set drafts", () => {617 it("supports iteration", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 618–621why, one step back618 const base = new Set([619 {id: 1, a: 1},620 {id: 2, a: 1}621 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 622–634why, one step back622 const findById = (set, id) => {623 for (const item of set) {624 if (item.id === id) return item625 }626 return null627 }628 const result = produce(base, draft => {629 const obj1 = findById(draft, 1)630 const obj2 = findById(draft, 2)631 obj1.a = 2632 obj2.a = 2633 })634 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 635–646why, one step back635 expect(base).toEqual(636 new Set([637 {id: 1, a: 1},638 {id: 2, a: 1}639 ])640 )641 expect(result).toEqual(642 new Set([643 {id: 1, a: 2},644 {id: 2, a: 2}645 ])646 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 647–649why, one step back647 })648649 it("supports 'entries'", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 650–653why, one step back650 const base = new Set([651 {id: 1, a: 1},652 {id: 2, a: 1}653 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 654–667why, one step back654 const findById = (set, id) => {655 for (const [item1, item2] of set.entries()) {656 expect(item1).toBe(item2)657 if (item1.id === id) return item1658 }659 return null660 }661 const result = produce(base, draft => {662 const obj1 = findById(draft, 1)663 const obj2 = findById(draft, 2)664 obj1.a = 2665 obj2.a = 2666 })667 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 668–679why, one step back668 expect(base).toEqual(669 new Set([670 {id: 1, a: 1},671 {id: 2, a: 1}672 ])673 )674 expect(result).toEqual(675 new Set([676 {id: 1, a: 2},677 {id: 2, a: 2}678 ])679 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 680–682why, one step back680 })681682 it("supports 'values'", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 683–686why, one step back683 const base = new Set([684 {id: 1, a: 1},685 {id: 2, a: 1}686 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 687–699why, one step back687 const findById = (set, id) => {688 for (const item of set.values()) {689 if (item.id === id) return item690 }691 return null692 }693 const result = produce(base, draft => {694 const obj1 = findById(draft, 1)695 const obj2 = findById(draft, 2)696 obj1.a = 2697 obj2.a = 2698 })699 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 700–711why, one step back700 expect(base).toEqual(701 new Set([702 {id: 1, a: 1},703 {id: 2, a: 1}704 ])705 )706 expect(result).toEqual(707 new Set([708 {id: 1, a: 2},709 {id: 2, a: 2}710 ])711 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 712–714why, one step back712 })713714 it("supports 'keys'", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 715–718why, one step back715 const base = new Set([716 {id: 1, a: 1},717 {id: 2, a: 1}718 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 719–731why, one step back719 const findById = (set, id) => {720 for (const item of set.keys()) {721 if (item.id === id) return item722 }723 return null724 }725 const result = produce(base, draft => {726 const obj1 = findById(draft, 1)727 const obj2 = findById(draft, 2)728 obj1.a = 2729 obj2.a = 2730 })731 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 732–743why, one step back732 expect(base).toEqual(733 new Set([734 {id: 1, a: 1},735 {id: 2, a: 1}736 ])737 )738 expect(result).toEqual(739 new Set([740 {id: 1, a: 2},741 {id: 2, a: 2}742 ])743 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 744–746why, one step back744 })745746 it("supports forEach with mutation after reads", () => {feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 747–750why, one step back747 const base = new Set([748 {id: 1, a: 1},749 {id: 2, a: 2}750 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 751–764why, one step back751 const result = produce(base, draft => {752 let sum1 = 0753 draft.forEach(({a}) => {754 sum1 += a755 })756 expect(sum1).toBe(3)757 let sum2 = 0758 draft.forEach(item => {759 item.a += 10760 sum2 += item.a761 })762 expect(sum2).toBe(23)763 })764 expect(result).not.toBe(base)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 765–776why, one step back765 expect(base).toEqual(766 new Set([767 {id: 1, a: 1},768 {id: 2, a: 2}769 ])770 )771 expect(result).toEqual(772 new Set([773 {id: 1, a: 11},774 {id: 2, a: 12}775 ])776 )feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 777–790why, one step back777 })778779 it("state stays the same if the same item is added", () => {780 const nextState = produce(baseState, s => {781 s.aSet.add("Luke")782 })783 expect(nextState).toBe(baseState)784 expect(nextState.aSet).toBe(baseState.aSet)785 })786787 it("can add new items", () => {788 const nextState = produce(baseState, s => {789 // Set.prototype.set should return the Set itself790 const res = s.aSet.add("force")Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
line 791why, one step back791 if (!global.USES_BUILD) expect(res).toBe(s.aSet[DRAFT_STATE].draft_)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 792–812why, one step back792 })793 expect(nextState).not.toBe(baseState)794 expect(nextState.aSet).not.toBe(baseState.aSet)795 expect(baseState.aSet.has("force")).toBe(false)796 expect(nextState.aSet.has("force")).toBe(true)797 })798799 it("returns 'size'", () => {800 const nextState = produce(baseState, s => {801 s.aSet.add("newKey")802 expect(s.aSet.size).toBe(baseState.aSet.size + 1)803 })804 expect(nextState).not.toBe(baseState)805 expect(nextState.aSet).not.toBe(baseState.aSet)806 expect(nextState.aSet.has("newKey")).toBe(true)807 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)808 })809810 it("can use 'delete' to remove items", () => {811 const nextState = produce(baseState, s => {812 expect(s.aSet.has("Luke")).toBe(true)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 813–814why, one step back813 expect(s.aSet.delete("Luke")).toBe(true)814 expect(s.aSet.delete("Luke")).toBe(false)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 815–819why, one step back815 expect(s.aSet.has("Luke")).toBe(false)816 })817 expect(nextState.aSet).not.toBe(baseState.aSet)818 expect(baseState.aSet.has("Luke")).toBe(true)819 expect(nextState.aSet.has("Luke")).toBe(false)feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 820why, one step back820 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 821–854why, one step back821 })822823 it("can use 'clear' to remove items", () => {824 const nextState = produce(baseState, s => {825 expect(s.aSet.size).not.toBe(0)826 s.aSet.clear()827 expect(s.aSet.size).toBe(0)828 })829 expect(nextState.aSet).not.toBe(baseState.aSet)830 expect(baseState.aSet.size).not.toBe(0)831 expect(nextState.aSet.size).toBe(0)832 })833834 it("supports 'has'", () => {835 const nextState = produce(baseState, s => {836 expect(s.aSet.has("newKey")).toBe(false)837 s.aSet.add("newKey")838 expect(s.aSet.has("newKey")).toBe(true)839 })840 expect(nextState).not.toBe(baseState)841 expect(nextState.aSet).not.toBe(baseState.aSet)842 expect(baseState.aSet.has("newKey")).toBe(false)843 expect(nextState.aSet.has("newKey")).toBe(true)844 })845846 it("supports nested sets", () => {847 const base = new Set([new Set(["Serenity"])])848 const result = produce(base, draft => {849 draft.forEach(nestedItem => nestedItem.add("Firefly"))850 })851 expect(result).not.toBe(base)852 expect(base).toEqual(new Set([new Set(["Serenity"])]))853 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))854 })feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 855–873why, one step back855856 it("supports has / delete on elements from the original", () => {857 const obj = {}858 const set = new Set([obj])859 const next = produce(set, d => {860 expect(d.has(obj)).toBe(true)861 d.add(3)862 expect(d.has(obj)).toBe(true)863 d.delete(obj)864 expect(d.has(obj)).toBe(false)865 })866 expect(next).toEqual(new Set([3]))867 })868869 it("revokes sets", () => {870 let m871 produce(baseState, s => {872 m = s.aSet873 })Errors for prodMichel Weststratebefore adoption67565dd
lines 874–875why, one step back874 expect(() => m.has("x")).toThrowErrorMatchingSnapshot()875 expect(() => m.add("x")).toThrowErrorMatchingSnapshot()fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a
lines 876–882why, one step back876 })877878 it("does support instanceof Set", () => {879 const set = new Set()880 produce(set, d => {881 expect(d instanceof Set).toBeTruthy()882 })feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
line 883why, one step back883 })feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 884–885why, one step back884 })885style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 886–910why, one step back886 it("supports `immerable` symbol on constructor", () => {887 class One {}888 One[immerable] = true889 const baseState = new One()890 const nextState = produce(baseState, draft => {891 expect(draft).not.toBe(baseState)892 draft.foo = true893 })894 expect(nextState).not.toBe(baseState)895 expect(nextState.foo).toBeTruthy()896 })897898 it("preserves symbol properties", () => {899 const test = Symbol("test")900 const baseState = {[test]: true}901 const nextState = produce(baseState, s => {902 expect(s[test]).toBeTruthy()903 s.foo = true904 })905 expect(nextState).toEqual({906 [test]: true,907 foo: true908 })909 })910chore: verify build during testMichel Weststratebefore adoptionef8990b
lines 911–933why, one step back911 if (!global.USES_BUILD)912 it("preserves non-enumerable properties", () => {913 const baseState = {}914 // Non-enumerable object property915 Object.defineProperty(baseState, "foo", {916 value: {a: 1},917 enumerable: false918 })919 // Non-enumerable primitive property920 Object.defineProperty(baseState, "bar", {921 value: 1,922 enumerable: false923 })924 const nextState = produce(baseState, s => {925 expect(s.foo).toBeTruthy()926 expect(isEnumerable(s, "foo")).toBeFalsy()927 s.bar++928 expect(isEnumerable(s, "foo")).toBeFalsy()929 s.foo.a++930 expect(isEnumerable(s, "foo")).toBeFalsy()931 })932 expect(nextState.foo).toBeTruthy()933 expect(isEnumerable(nextState, "foo")).toBeFalsy()style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 934–970why, one step back934 })935936 it("throws on computed properties", () => {937 const baseState = {}938 Object.defineProperty(baseState, "foo", {939 get: () => {},940 enumerable: true941 })942 expect(() => {943 produce(baseState, s => {944 // Proxies only throw once a change is made.945 if (useProxies) {946 s.modified = true947 }948 })949 }).toThrowErrorMatchingSnapshot()950 })951952 it("allows inherited computed properties", () => {953 const proto = {}954 Object.defineProperty(proto, "foo", {955 get() {956 return this.bar957 },958 set(val) {959 this.bar = val960 }961 })962 const baseState = Object.create(proto)963 produce(baseState, s => {964 expect(s.bar).toBeUndefined()965 s.foo = {}966 expect(s.bar).toBeDefined()967 expect(s.foo).toBe(s.bar)968 })969 })970Optimization: stop recursing if there are no drafts leftMichel Weststratebefore adoptionebda6f8
lines 971–1015why, one step back971 it("optimization: does not visit properties of new data structures if autofreeze is disabled and no drafts are unfinalized", () => {972 const newData = {}973 Object.defineProperty(newData, "x", {974 enumerable: true,975 get() {976 throw new Error("visited!")977 }978 })979980 const run = () =>981 produce({}, d => {982 d.data = newData983 })984 if (autoFreeze) {985 expect(run).toThrow("visited!")986 } else {987 expect(run).not.toThrow("visited!")988 }989 })990991 it("same optimization doesn't cause draft from nested producers to be unfinished", () => {992 const base = {993 y: 1,994 child: {995 x: 1996 }997 }998 const wrap = produce(draft => {999 return {1000 wrapped: draft1001 }1002 })10031004 const res = produce(base, draft => {1005 draft.y++1006 draft.child = wrap(draft.child)1007 draft.child.wrapped.x++1008 })10091010 expect(res).toEqual({1011 y: 2,1012 child: {wrapped: {x: 2}}1013 })1014 })1015style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1016–1170why, one step back1016 it("supports a base state with multiple references to an object", () => {1017 const obj = {}1018 const res = produce({a: obj, b: obj}, d => {1019 // Two drafts are created for each occurrence of an object in the base state.1020 expect(d.a).not.toBe(d.b)1021 d.a.z = true1022 expect(d.b.z).toBeUndefined()1023 })1024 expect(res.b).toBe(obj)1025 expect(res.a).not.toBe(res.b)1026 expect(res.a.z).toBeTruthy()1027 })10281029 // NOTE: Except the root draft.1030 it("supports multiple references to any modified draft", () => {1031 const next = produce({a: {b: 1}}, d => {1032 d.a.b++1033 d.b = d.a1034 })1035 expect(next.a).toBe(next.b)1036 })10371038 it("can rename nested objects (no changes)", () => {1039 const nextState = produce({obj: {}}, s => {1040 s.foo = s.obj1041 delete s.obj1042 })1043 expect(nextState).toEqual({foo: {}})1044 })10451046 // Very similar to the test before, but the reused object has one1047 // property changed, one added, and one removed.1048 it("can rename nested objects (with changes)", () => {1049 const nextState = produce({obj: {a: 1, b: 1}}, s => {1050 s.obj.a = true // change1051 delete s.obj.b // delete1052 s.obj.c = true // add10531054 s.foo = s.obj1055 delete s.obj1056 })1057 expect(nextState).toEqual({foo: {a: true, c: true}})1058 })10591060 it("can nest a draft in a new object (no changes)", () => {1061 const baseState = {obj: {}}1062 const nextState = produce(baseState, s => {1063 s.foo = {bar: s.obj}1064 delete s.obj1065 })1066 expect(nextState.foo.bar).toBe(baseState.obj)1067 })10681069 it("can nest a modified draft in a new object", () => {1070 const nextState = produce({obj: {a: 1, b: 1}}, s => {1071 s.obj.a = true // change1072 delete s.obj.b // delete1073 s.obj.c = true // add10741075 s.foo = {bar: s.obj}1076 delete s.obj1077 })1078 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1079 })10801081 it("supports assigning undefined to an existing property", () => {1082 const nextState = produce(baseState, s => {1083 s.aProp = undefined1084 })1085 expect(nextState).not.toBe(baseState)1086 expect(nextState.aProp).toBe(undefined)1087 })10881089 it("supports assigning undefined to a new property", () => {1090 const baseState = {}1091 const nextState = produce(baseState, s => {1092 s.aProp = undefined1093 })1094 expect(nextState).not.toBe(baseState)1095 expect(nextState.aProp).toBe(undefined)1096 })10971098 // NOTE: ES5 drafts only protect existing properties when revoked.1099 it("revokes the draft once produce returns", () => {1100 const expectRevoked = (fn, shouldThrow = true) => {1101 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()1102 else expect(fn).not.toThrow()1103 }11041105 // Test object drafts:1106 let draft1107 produce({a: 1, b: 1}, s => {1108 draft = s1109 delete s.b1110 })11111112 // Access known property on object draft.1113 expectRevoked(() => {1114 draft.a1115 })11161117 // Assign known property on object draft.1118 expectRevoked(() => {1119 draft.a = true1120 })11211122 // Access unknown property on object draft.1123 expectRevoked(() => {1124 draft.z1125 }, useProxies)11261127 // Assign unknown property on object draft.1128 expectRevoked(() => {1129 draft.z = true1130 }, useProxies)11311132 // Test array drafts:1133 produce([1, 2], s => {1134 draft = s1135 s.pop()1136 })11371138 // Access known index of an array draft.1139 expectRevoked(() => {1140 draft[0]1141 })11421143 // Assign known index of an array draft.1144 expectRevoked(() => {1145 draft[0] = true1146 })11471148 // Access unknown index of an array draft.1149 expectRevoked(() => {1150 draft[1]1151 }, useProxies)11521153 // Assign unknown index of an array draft.1154 expectRevoked(() => {1155 draft[1] = true1156 }, useProxies)1157 })11581159 it("can access a child draft that was created before the draft was modified", () => {1160 produce({a: {}}, s => {1161 const before = s.a1162 s.b = 11163 expect(s.a).toBe(before)1164 })1165 })11661167 it("should reflect all changes made in the draft immediately", () => {1168 produce(baseState, draft => {1169 draft.anArray[0] = 51170 draft.anArray.unshift("test")chore: verify build during testMichel Weststratebefore adoptionef8990b
lines 1171–1178why, one step back1171 if (!global.USES_BUILD)1172 expect(enumerableOnly(draft.anArray)).toEqual([1173 "test",1174 5,1175 2,1176 {c: 3},1177 11178 ])style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1179–1430why, one step back1179 draft.stuffz = "coffee"1180 expect(draft.stuffz).toBe("coffee")1181 })1182 })11831184 if (useProxies)1185 it("throws when Object.defineProperty() is used on drafts", () => {1186 expect(() => {1187 produce({}, draft => {1188 Object.defineProperty(draft, "xx", {1189 enumerable: true,1190 writeable: true,1191 value: 21192 })1193 })1194 }).toThrowErrorMatchingSnapshot()1195 })11961197 it("should handle constructor correctly", () => {1198 const baseState = {1199 arr: new Array(),1200 obj: new Object()1201 }1202 const result = produce(baseState, draft => {1203 draft.arrConstructed = draft.arr.constructor(1)1204 draft.objConstructed = draft.obj.constructor(1)1205 })1206 expect(result.arrConstructed).toEqual(new Array().constructor(1))1207 expect(result.objConstructed).toEqual(new Object().constructor(1))1208 })12091210 it("should handle equality correctly - 1", () => {1211 const baseState = {1212 y: 3 / 0,1213 z: NaN1214 }1215 const nextState = produce(baseState, draft => {1216 draft.y = 4 / 01217 draft.z = NaN1218 })1219 expect(nextState).toBe(baseState)1220 })12211222 it("should handle equality correctly - 2", () => {1223 const baseState = {1224 x: -01225 }1226 const nextState = produce(baseState, draft => {1227 draft.x = +01228 })1229 expect(nextState).not.toBe(baseState)1230 expect(nextState).not.toEqual(baseState)1231 })12321233 // AKA: recursive produce calls1234 describe("nested producers", () => {1235 describe("when base state is not a draft", () => {1236 // This test ensures the global state used to manage proxies is1237 // never left in a corrupted state by a nested `produce` call.1238 it("never affects its parent producer implicitly", () => {1239 const base = {obj: {a: 1}}1240 const next = produce(base, draft => {1241 // Notice how `base.obj` is passed, not `draft.obj`1242 const obj2 = produce(base.obj, draft2 => {1243 draft2.a = 01244 })1245 expect(obj2.a).toBe(0)1246 expect(draft.obj.a).toBe(1) // effects should not be visible outside1247 })1248 expect(next).toBe(base)1249 })1250 })12511252 describe("when base state is a draft", () => {1253 it("always wraps the draft in a new draft", () => {1254 produce({}, parent => {1255 produce(parent, child => {1256 expect(child).not.toBe(parent)1257 expect(isDraft(child)).toBeTruthy()1258 expect(original(child)).toBe(parent)1259 })1260 })1261 })12621263 // Reported by: https://github.com/mweststrate/immer/issues/3431264 it("ensures each property is drafted", () => {1265 produce({a: {}, b: {}}, parent => {1266 parent.a // Access "a" but not "b"1267 produce(parent, child => {1268 child.c = 11269 expect(isDraft(child.a)).toBeTruthy()1270 expect(isDraft(child.b)).toBeTruthy()1271 })1272 })1273 })12741275 it("preserves any pending changes", () => {1276 produce({a: 1, b: 1, d: 1}, parent => {1277 parent.b = 21278 parent.c = 21279 delete parent.d1280 produce(parent, child => {1281 expect(child.a).toBe(1) // unchanged1282 expect(child.b).toBe(2) // changed1283 expect(child.c).toBe(2) // added1284 expect(child.d).toBeUndefined() // deleted1285 })1286 })1287 })1288 })12891290 describe("when base state contains a draft", () => {1291 it("wraps unowned draft with its own draft", () => {1292 produce({a: {}}, parent => {1293 produce({a: parent.a}, child => {1294 expect(child.a).not.toBe(parent.a)1295 expect(isDraft(child.a)).toBeTruthy()1296 expect(original(child.a)).toBe(parent.a)1297 })1298 })1299 })13001301 it("returns unowned draft if no changes were made", () => {1302 produce({a: {}}, parent => {1303 const result = produce({a: parent.a}, () => {})1304 expect(result.a).toBe(parent.a)1305 })1306 })13071308 it("clones the unowned draft when changes are made", () => {1309 produce({a: {}}, parent => {1310 const result = produce({a: parent.a}, child => {1311 child.a.b = 11312 })1313 expect(result.a).not.toBe(parent.a)1314 expect(result.a.b).toBe(1)1315 expect("b" in parent.a).toBeFalsy()1316 })1317 })13181319 // We cannot auto-freeze the result of a nested producer,1320 // because it may contain a draft from a parent producer.1321 it("never auto-freezes the result", () => {1322 produce({a: {}}, parent => {1323 const r = produce({a: parent.a}, child => {1324 child.b = 1 // Ensure a copy is returned.1325 })1326 expect(Object.isFrozen(r)).toBeFalsy()1327 })1328 })1329 })13301331 // "Upvalues" are variables from a parent scope.1332 it("does not finalize upvalue drafts", () => {1333 produce({a: {}, b: {}}, parent => {1334 expect(produce({}, () => parent)).toBe(parent)1335 parent.x // Ensure proxy not revoked.13361337 expect(produce({}, () => [parent])[0]).toBe(parent)1338 parent.x // Ensure proxy not revoked.13391340 expect(produce({}, () => parent.a)).toBe(parent.a)1341 parent.a.x // Ensure proxy not revoked.13421343 // Modified parent test1344 parent.c = 11345 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1346 parent.b.x // Ensure proxy not revoked.1347 })1348 })13491350 it("works with interweaved Immer instances", () => {1351 const options = {useProxies, autoFreeze}1352 const one = createPatchedImmer(options)1353 const two = createPatchedImmer(options)13541355 const base = {}1356 const result = one.produce(base, s1 =>1357 two.produce({s1}, s2 => {1358 expect(original(s2.s1)).toBe(s1)1359 s2.n = 11360 s2.s1 = one.produce({s2}, s3 => {1361 expect(original(s3.s2)).toBe(s2)1362 expect(original(s3.s2.s1)).toBe(s2.s1)1363 return s3.s2.s11364 })1365 })1366 )1367 expect(result.n).toBe(1)1368 expect(result.s1).toBe(base)1369 })1370 })13711372 if (useProxies)1373 it("throws when Object.setPrototypeOf() is used on a draft", () => {1374 produce({}, draft => {1375 expect(() =>1376 Object.setPrototypeOf(draft, Array)1377 ).toThrowErrorMatchingSnapshot()1378 })1379 })13801381 it("supports the 'in' operator", () => {1382 produce(baseState, draft => {1383 // Known property1384 expect("anArray" in draft).toBe(true)1385 expect(Reflect.has(draft, "anArray")).toBe(true)13861387 // Unknown property1388 expect("bla" in draft).toBe(false)1389 expect(Reflect.has(draft, "bla")).toBe(false)13901391 // Known index1392 expect(0 in draft.anArray).toBe(true)1393 expect("0" in draft.anArray).toBe(true)1394 expect(Reflect.has(draft.anArray, 0)).toBe(true)1395 expect(Reflect.has(draft.anArray, "0")).toBe(true)13961397 // Unknown index1398 expect(17 in draft.anArray).toBe(false)1399 expect("17" in draft.anArray).toBe(false)1400 expect(Reflect.has(draft.anArray, 17)).toBe(false)1401 expect(Reflect.has(draft.anArray, "17")).toBe(false)1402 })1403 })14041405 it("'this' should not be bound anymore - 1", () => {1406 const base = {x: 3}1407 const next1 = produce(base, function() {1408 expect(this).toBe(undefined)1409 })1410 })14111412 it("'this' should not be bound anymore - 2", () => {1413 const incrementor = produce(function() {1414 expect(this).toBe(undefined)1415 })1416 incrementor()1417 })14181419 it("should be possible to use dynamic bound this", () => {1420 const world = {1421 counter: {count: 1},1422 inc: produce(function(draft) {1423 expect(this).toBe(world)1424 draft.counter.count = this.counter.count + 11425 })1426 }14271428 expect(world.inc(world).counter.count).toBe(2)1429 })1430Cleanup. Don't recurse into frozen data structuresMichel Weststratebefore adoptiond32cb97
lines 1431–1448why, one step back1431 it("doesnt recurse into frozen structures if external data is frozen", () => {1432 const frozen = {}1433 Object.defineProperty(frozen, "x", {1434 get() {1435 throw "oops"1436 },1437 enumerable: true,1438 configurable: true1439 })1440 Object.freeze(frozen)14411442 expect(() => {1443 produce({}, d => {1444 d.x = frozen1445 })1446 }).not.toThrow()1447 })1448style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1449–1480why, one step back1449 // See here: https://github.com/mweststrate/immer/issues/891450 it("supports the spread operator", () => {1451 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1452 const result = produce(base, draft => {1453 draft.foo = {x: 1, ...draft.foo, y: 1}1454 draft.bar = [1, ...draft.bar, 1]1455 })1456 expect(result).toEqual({1457 foo: {x: 0, y: 1},1458 bar: [1, 0, 0, 1]1459 })1460 })14611462 it("processes with lodash.set", () => {1463 const base = [{id: 1, a: 1}]1464 const result = produce(base, draft => {1465 lodash.set(draft, "[0].a", 2)1466 })1467 expect(base[0].a).toEqual(1)1468 expect(result[0].a).toEqual(2)1469 })14701471 it("processes with lodash.find", () => {1472 const base = [{id: 1, a: 1}]1473 const result = produce(base, draft => {1474 const obj1 = lodash.find(draft, {id: 1})1475 lodash.set(obj1, "a", 2)1476 })1477 expect(base[0].a).toEqual(1)1478 expect(result[0].a).toEqual(2)1479 })1480feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 1481–1494why, one step back1481 it("does not draft external data", () => {1482 const externalData = {x: 3}1483 const base = {}1484 const next = produce(base, draft => {1485 // potentially, we *could* draft external data automatically, but only if those statements are not switched...1486 draft.y = externalData1487 draft.y.x += 11488 externalData.x += 11489 })1490 expect(next).toEqual({y: {x: 5}})1491 expect(externalData.x).toBe(5)1492 expect(next.y).toBe(externalData)1493 })1494chore: added test for #491Michel Weststratebefore adoption788dc03
lines 1495–1509why, one step back1495 it("does not create new state unnecessary, #491", () => {1496 const a = {highlight: true}1497 const next1 = produce(a, draft => {1498 draft.highlight = false1499 draft.highlight = true1500 })1501 // See explanation in issue1502 expect(next1).not.toBe(a)15031504 const next2 = produce(a, draft => {1505 draft.highlight = true1506 })1507 expect(next2).toBe(a)1508 })1509test: tried to reproduce #469Michel Weststratebefore adoptione504e0b
line 1510why, one step back1510 autoFreeze &&chore: add test for #462Michel Weststratebefore adoptionce6a3c2
lines 1511–1528why, one step back1511 test.skip("issue #462 - frozen", () => {1512 var origin = {1513 a: {1514 value: "no"1515 },1516 b: {1517 value: "no"1518 }1519 }1520 var im = produce(origin, origin => {1521 origin.a.value = "im"1522 })1523 expect(() => (origin.b.value = "yes")).toThrow() // should throw!1524 // to prevent this...:1525 // expect(im.b.value).toBe('no');1526 })15271528 autoFreeze &&test: tried to reproduce #469Michel Weststratebefore adoptione504e0b
lines 1529–1546why, one step back1529 test("issue #469, state not frozen", () => {1530 const project = produce(1531 {1532 id: 1,1533 tracks: [{id: 1}]1534 },1535 () => {}1536 )15371538 expect(() => {1539 project.id = 2 // Does not throw error1540 }).toThrowError("Cannot assign to read only property 'id'")15411542 expect(() => {1543 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1544 }).toThrowError("Cannot assign to read only property 'id'")1545 })1546style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1547–1804why, one step back1547 describe("recipe functions", () => {1548 it("can return a new object", () => {1549 const base = {x: 3}1550 const res = produce(base, d => {1551 return {x: d.x + 1}1552 })1553 expect(res).not.toBe(base)1554 expect(res).toEqual({x: 4})1555 })15561557 it("can return the draft", () => {1558 const base = {x: 3}1559 const res = produce(base, d => {1560 d.x = 41561 return d1562 })1563 expect(res).not.toBe(base)1564 expect(res).toEqual({x: 4})1565 })15661567 it("can return an unmodified child draft", () => {1568 const base = {a: {}}1569 const res = produce(base, d => {1570 return d.a1571 })1572 expect(res).toBe(base.a)1573 })15741575 // TODO: Avoid throwing if only the child draft was modified.1576 it("cannot return a modified child draft", () => {1577 const base = {a: {}}1578 expect(() => {1579 produce(base, d => {1580 d.a.b = 11581 return d.a1582 })1583 }).toThrowErrorMatchingSnapshot()1584 })15851586 it("can return a frozen object", () => {1587 const res = deepFreeze([{x: 3}])1588 expect(produce({}, () => res)).toBe(res)1589 })15901591 it("can return an object with two references to another object", () => {1592 const next = produce({}, d => {1593 const obj = {}1594 return {obj, arr: [obj]}1595 })1596 expect(next.obj).toBe(next.arr[0])1597 })15981599 it("can return an object with two references to an unmodified draft", () => {1600 const base = {a: {}}1601 const next = produce(base, d => {1602 return [d.a, d.a]1603 })1604 expect(next[0]).toBe(base.a)1605 expect(next[0]).toBe(next[1])1606 })16071608 it("cannot return an object that references itself", () => {1609 const res = {}1610 res.self = res1611 expect(() => {1612 produce(res, () => res.self)1613 }).toThrowErrorMatchingSnapshot()1614 })1615 })16161617 describe("async recipe function", () => {1618 it("can modify the draft", () => {1619 const base = {a: 0, b: 0}1620 return produce(base, async d => {1621 d.a = 11622 await Promise.resolve()1623 d.b = 11624 }).then(res => {1625 expect(res).not.toBe(base)1626 expect(res).toEqual({a: 1, b: 1})1627 })1628 })16291630 it("works with rejected promises", () => {1631 let draft1632 const base = {a: 0, b: 0}1633 const err = new Error("passed")1634 return produce(base, d => {1635 draft = d1636 draft.b = 11637 return Promise.reject(err)1638 }).then(1639 () => {1640 throw "failed"1641 },1642 e => {1643 expect(e).toBe(err)1644 expect(() => draft.a).toThrowErrorMatchingSnapshot()1645 }1646 )1647 })16481649 it("supports recursive produce calls after await", () => {1650 const base = {obj: {k: 1}}1651 return produce(base, d => {1652 const obj = d.obj1653 delete d.obj1654 return Promise.resolve().then(() => {1655 d.a = produce({}, d => {1656 d.b = obj // Assign a draft owned by the parent scope.1657 })16581659 // Auto-freezing is prevented when an unowned draft exists.1660 expect(Object.isFrozen(d.a)).toBeFalsy()16611662 // Ensure `obj` is not revoked.1663 obj.c = 11664 })1665 }).then(res => {1666 expect(res).not.toBe(base)1667 expect(res).toEqual({1668 a: {b: {k: 1, c: 1}}1669 })1670 })1671 })1672 })16731674 it("throws when the draft is modified and another object is returned", () => {1675 const base = {x: 3}1676 expect(() => {1677 produce(base, draft => {1678 draft.x = 41679 return {x: 5}1680 })1681 }).toThrowErrorMatchingSnapshot()1682 })16831684 it("should fix #117 - 1", () => {1685 const reducer = (state, action) =>1686 produce(state, draft => {1687 switch (action.type) {1688 case "SET_STARTING_DOTS":1689 return draft.availableStartingDots.map(a => a)1690 default:1691 break1692 }1693 })1694 const base = {1695 availableStartingDots: [1696 {dots: 4, count: 1},1697 {dots: 3, count: 2},1698 {dots: 2, count: 3},1699 {dots: 1, count: 4}1700 ]1701 }1702 const next = reducer(base, {type: "SET_STARTING_DOTS"})1703 expect(next).toEqual(base.availableStartingDots)1704 expect(next).not.toBe(base.availableStartingDots)1705 })17061707 it("should fix #117 - 2", () => {1708 const reducer = (state, action) =>1709 produce(state, draft => {1710 switch (action.type) {1711 case "SET_STARTING_DOTS":1712 return {1713 dots: draft.availableStartingDots.map(a => a)1714 }1715 default:1716 break1717 }1718 })1719 const base = {1720 availableStartingDots: [1721 {dots: 4, count: 1},1722 {dots: 3, count: 2},1723 {dots: 2, count: 3},1724 {dots: 1, count: 4}1725 ]1726 }1727 const next = reducer(base, {type: "SET_STARTING_DOTS"})1728 expect(next).toEqual({dots: base.availableStartingDots})1729 })17301731 it("cannot always detect noop assignments - 0", () => {1732 const baseState = {x: {y: 3}}1733 const nextState = produce(baseState, d => {1734 const a = d.x1735 d.x = a1736 })1737 expect(nextState).toBe(baseState)1738 })17391740 it("cannot always detect noop assignments - 1", () => {1741 const baseState = {x: {y: 3}}1742 const nextState = produce(baseState, d => {1743 const a = d.x1744 d.x = 41745 d.x = a1746 })1747 // Ideally, this should actually be the same instances1748 // but this would be pretty expensive to detect,1749 // so we don't atm1750 expect(nextState).not.toBe(baseState)1751 })17521753 it("cannot always detect noop assignments - 2", () => {1754 const baseState = {x: {y: 3}}1755 const nextState = produce(baseState, d => {1756 const a = d.x1757 const stuff = a.y + 31758 d.x = 41759 d.x = a1760 })1761 // Ideally, this should actually be the same instances1762 // but this would be pretty expensive to detect,1763 // so we don't atm1764 expect(nextState).not.toBe(baseState)1765 })17661767 it("cannot always detect noop assignments - 3", () => {1768 const baseState = {x: 3}1769 const nextState = produce(baseState, d => {1770 d.x = 31771 })1772 expect(nextState).toBe(baseState)1773 })17741775 it("cannot always detect noop assignments - 4", () => {1776 const baseState = {x: 3}1777 const nextState = produce(baseState, d => {1778 d.x = 41779 d.x = 31780 })1781 // Ideally, this should actually be the same instances1782 // but this would be pretty expensive to detect,1783 // so we don't atm1784 expect(nextState).not.toBe(baseState)1785 })17861787 it("cannot produce undefined by returning undefined", () => {1788 const base = 31789 expect(produce(base, () => 4)).toBe(4)1790 expect(produce(base, () => null)).toBe(null)1791 expect(produce(base, () => undefined)).toBe(3)1792 expect(produce(base, () => {})).toBe(3)1793 expect(produce(base, () => nothing)).toBe(undefined)17941795 expect(produce({}, () => undefined)).toEqual({})1796 expect(produce({}, () => nothing)).toBe(undefined)1797 expect(produce(3, () => nothing)).toBe(undefined)17981799 expect(produce(() => undefined)({})).toEqual({})1800 expect(produce(() => nothing)({})).toBe(undefined)1801 expect(produce(() => nothing)(3)).toBe(undefined)1802 })18031804 describe("base state type", () => {chore: verify build during testMichel Weststratebefore adoptionef8990b
line 1805why, one step back1805 if (!global.USES_BUILD) testObjectTypes(produce)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1806–1818why, one step back1806 testLiteralTypes(produce)1807 })18081809 afterEach(() => {1810 expect(baseState).toBe(origBaseState)1811 expect(baseState).toEqual(createBaseState())1812 })18131814 class Foo {}1815 function createBaseState() {1816 const data = {1817 anInstance: new Foo(),1818 anArray: [3, 2, {c: 3}, 1],feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1819–1830why, one step back1819 aMap: new Map([1820 ["jedi", {name: "Luke", skill: 10}],1821 ["jediTotal", 42],1822 ["force", "these aren't the droids you're looking for"]1823 ]),1824 aSet: new Set([1825 "Luke",1826 42,1827 {1828 jedi: "Yoda"1829 }1830 ]),style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1831–1842why, one step back1831 aProp: "hi",1832 anObject: {1833 nested: {1834 yummie: true1835 },1836 coffee: false1837 }1838 }1839 return autoFreeze ? deepFreeze(data) : data1840 }1841 })1842fix: Fixed issue where drafts from nested producers were frozen. Fixes #522, #524Michel Weststratebefore adoptionacc5e54
lines 1843–1936why, one step back1843 it(`works with spread #524 - ${name}`, () => {1844 const state = {1845 level1: {1846 level2: {1847 level3: "data"1848 }1849 }1850 }18511852 const nextState = produce(state, draft => {1853 return {...draft}1854 })1855 const nextState1 = produce(state, draft => {1856 const newLevel1 = produce(draft.level1, level1Draft => {1857 return {...level1Draft}1858 })1859 draft.level1 = newLevel11860 })18611862 const nextState2 = produce(state, draft => {1863 const newLevel1 = produce(draft.level1, level1Draft => {1864 return {...level1Draft}1865 })1866 return {1867 level1: newLevel11868 }1869 })18701871 const nextState3 = produce(state, draft => {1872 const newLevel1 = produce(draft.level1, level1Draft => {1873 return Object.assign({}, level1Draft)1874 })1875 return Object.assign(draft, {1876 level1: newLevel11877 })1878 })18791880 const expected = {level1: {level2: {level3: "data"}}}1881 expect(nextState1).toEqual(expected)1882 expect(nextState2).toEqual(expected)1883 expect(nextState3).toEqual(expected)1884 })18851886 it(`Something with nested producers #522 ${name}`, () => {1887 function initialStateFactory() {1888 return {1889 substate: {1890 array: [1891 {id: "id1", value: 0},1892 {id: "id2", value: 0}1893 ]1894 },1895 array: [1896 {id: "id1", value: 0},1897 {id: "id2", value: 0}1898 ]1899 }1900 }19011902 const globalProducer = produce(draft => {1903 draft.substate = subProducer(draft.substate)1904 draft.array = arrayProducer(draft.array)1905 }, initialStateFactory())19061907 const subProducer = produce(draftSubState => {1908 draftSubState.array = arrayProducer(draftSubState.array)1909 })19101911 const arrayProducer = produce(draftArray => {1912 draftArray[0].value += 51913 })19141915 {1916 const state = globalProducer(undefined)1917 expect(state.array[0].value).toBe(5)1918 expect(state.array.length).toBe(2)1919 expect(state.array[1]).toMatchObject({1920 id: "id2",1921 value: 01922 })1923 }19241925 {1926 const state = globalProducer(undefined)1927 expect(state.substate.array[0].value).toBe(5)1928 expect(state.substate.array.length).toBe(2)1929 expect(state.substate.array[1]).toMatchObject({1930 id: "id2",1931 value: 01932 })1933 expect(state.substate.array).toMatchObject(state.array)1934 }1935 })1936style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1937–1974why, one step back1937 describe(`isDraft - ${name}`, () => {1938 it("returns true for object drafts", () => {1939 produce({}, state => {1940 expect(isDraft(state)).toBeTruthy()1941 })1942 })1943 it("returns true for array drafts", () => {1944 produce([], state => {1945 expect(isDraft(state)).toBeTruthy()1946 })1947 })1948 it("returns true for objects nested in object drafts", () => {1949 produce({a: {b: {}}}, state => {1950 expect(isDraft(state.a)).toBeTruthy()1951 expect(isDraft(state.a.b)).toBeTruthy()1952 })1953 })1954 it("returns false for new objects added to a draft", () => {1955 produce({}, state => {1956 state.a = {}1957 expect(isDraft(state.a)).toBeFalsy()1958 })1959 })1960 it("returns false for objects returned by the producer", () => {1961 const object = produce(null, Object.create)1962 expect(isDraft(object)).toBeFalsy()1963 })1964 it("returns false for arrays returned by the producer", () => {1965 const array = produce(null, _ => [])1966 expect(isDraft(array)).toBeFalsy()1967 })1968 it("returns false for object drafts returned by the producer", () => {1969 const object = produce({}, state => state)1970 expect(isDraft(object)).toBeFalsy()1971 })1972 it("returns false for array drafts returned by the producer", () => {1973 const array = produce([], state => state)1974 expect(isDraft(array)).toBeFalsy()feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1975–1983why, one step back1975 })1976 })19771978 describe(`complex nesting map / set / object`, () => {1979 const a = {a: 1}1980 const b = {b: 2}1981 const c = {c: 3}1982 const set1 = new Set([a, b])1983 const set2 = new Set([c])feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 1984–1987why, one step back1984 const map = new Map([1985 ["set1", set1],1986 ["set2", set2]1987 ])feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1988–2036why, one step back1988 const base = {map}19891990 function first(set) {1991 return Array.from(set.values())[0]1992 }19931994 function second(set) {1995 return Array.from(set.values())[1]1996 }19971998 test(`modify deep object`, () => {1999 const [res, patches] = produceWithPatches(base, draft => {2000 const v = first(draft.map.get("set1"))The first 2,000 of 2,162 lines.