Skip to content
Myr

base.js

This file

Path

__tests__/base.js

2,120 lines · 54.5 KiB · JavaScript

Last changed by

Cleanup. Don't recurse into frozen data structuresMichel Weststratebefore adoptiond32cb97

History of this file

Take it

The walk stopped after 200 commits: lines older than b053637 point at it.

test: returning an upvalue draft from a nested produceraleclarsonbefore adoptionb053637

line 1why, one step back
1"use strict"

New build set. Current statsMichel Weststratebefore adoption9aec0fe

lines 2–9why, one step back
2import {
3 Immer,4 nothing,5 original,6 isDraft,7 immerable,8 enableAllPlugins9} from "../src/immer"

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

line 10why, one step back
10import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/internal"

test: returning an upvalue draft from a nested produceraleclarsonbefore adoptionb053637

lines 11–15why, one step back
11import 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 back
16
17enableAllPlugins()

test: returning an upvalue draft from a nested produceraleclarsonbefore adoptionb053637

line 18why, one step back
18

chore: improve more testsaleclarsonbefore adoption4f59b12

line 19why, one step back
19test("immer should have no dependencies", () => {

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 20why, one step back
20 expect(require("../package.json").dependencies).toBeUndefined()

chore: improve more testsaleclarsonbefore adoption4f59b12

line 21why, one step back
21})

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 22why, one step back
22

test: returning an upvalue draft from a nested produceraleclarsonbefore adoptionb053637

lines 23–24why, one step back
23runBaseTest("proxy (no freeze)", true, false)
24runBaseTest("proxy (autofreeze)", true, true)

added base tests for autofreeze + patch listenersMichel Weststratebefore adoption9f07525

line 25why, one step back
25runBaseTest("proxy (patch listener)", true, false, true)

test: returning an upvalue draft from a nested produceraleclarsonbefore adoptionb053637

line 26why, one step back
26runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)

Initial finalize cleanupMichel Weststratebefore adoption67ab3ab

line 27why, one step back
27

test: returning an upvalue draft from a nested produceraleclarsonbefore adoptionb053637

lines 28–29why, one step back
28runBaseTest("es5 (no freeze)", false, false)
29runBaseTest("es5 (autofreeze)", false, true)

added base tests for autofreeze + patch listenersMichel Weststratebefore adoption9f07525

line 30why, one step back
30runBaseTest("es5 (patch listener)", false, false, true)

test: returning an upvalue draft from a nested produceraleclarsonbefore adoptionb053637

line 31why, one step back
31runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 32why, one step back
32

test: returning an upvalue draft from a nested produceraleclarsonbefore adoptionb053637

line 33why, one step back
33function runBaseTest(name, useProxies, autoFreeze, useListener) {

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 34why, one step back
34 const listener = useListener ? function() {} : undefined

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 35why, one step back
35 const {produce, produceWithPatches} = createPatchedImmer({

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 36–45why, one step back
36 useProxies,
37 autoFreeze38 })3940 // When `useListener` is true, append a function to the arguments of every41 // uncurried `produce` call in every test. This makes tests easier to read.42 function createPatchedImmer(options) {43 const immer = new Immer(options)4445 const {produce} = immer

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 46–47why, one step back
46 immer.produce = function(...args) {
47 return typeof args[1] === "function" && args.length < 3

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 48–49why, one step back
48 ? produce(...args, listener)
49 : produce(...args)

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 50why, one step back
50 }

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 51–202why, one step back
51
52 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 back
203 const base = [
204 {id: 1, a: 1},205 {id: 2, a: 1}206 ]

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 207–317why, one step back
207 const findById = (collection, id) => {
208 for (const item of collection) {209 if (item.id === id) return item210 }211 return null212 }213 const result = produce(base, draft => {214 const obj1 = findById(draft, 1)215 const obj2 = findById(draft, 2)216 obj1.a = 2217 obj2.a = 2218 })219 expect(result[0].a).toEqual(2)220 expect(result[1].a).toEqual(2)221 })222223 it("can assign an index via bracket notation", () => {224 const nextState = produce(baseState, s => {225 s.anArray[3] = true226 })227 expect(nextState).not.toBe(baseState)228 expect(nextState.anArray).not.toBe(baseState.anArray)229 expect(nextState.anArray[3]).toEqual(true)230 })231232 it("can use splice() to both add and remove items", () => {233 const nextState = produce(baseState, s => {234 s.anArray.splice(1, 1, "a", "b")235 })236 expect(nextState.anArray).not.toBe(baseState.anArray)237 expect(nextState.anArray[1]).toBe("a")238 expect(nextState.anArray[2]).toBe("b")239 })240241 it("can truncate via the length property", () => {242 const baseLength = baseState.anArray.length243 const nextState = produce(baseState, s => {244 s.anArray.length = baseLength - 1245 })246 expect(nextState.anArray).not.toBe(baseState.anArray)247 expect(nextState.anArray.length).toBe(baseLength - 1)248 })249250 it("can extend via the length property", () => {251 const baseLength = baseState.anArray.length252 const nextState = produce(baseState, s => {253 s.anArray.length = baseLength + 1254 })255 expect(nextState.anArray).not.toBe(baseState.anArray)256 expect(nextState.anArray.length).toBe(baseLength + 1)257 })258259 // Reported here: https://github.com/mweststrate/immer/issues/116260 it("can pop then push", () => {261 const nextState = produce([1, 2, 3], s => {262 s.pop()263 s.push(100)264 })265 expect(nextState).toEqual([1, 2, 100])266 })267268 it("can be sorted", () => {269 const baseState = [3, 1, 2]270 const nextState = produce(baseState, s => {271 s.sort()272 })273 expect(nextState).not.toBe(baseState)274 expect(nextState).toEqual([1, 2, 3])275 })276277 it("supports modifying nested objects", () => {278 const baseState = [{a: 1}, {}]279 const nextState = produce(baseState, s => {280 s[0].a++281 s[1].a = 0282 })283 expect(nextState).not.toBe(baseState)284 expect(nextState[0].a).toBe(2)285 expect(nextState[1].a).toBe(0)286 })287288 it("never preserves non-numeric properties", () => {289 const baseState = []290 baseState.x = 7291 const nextState = produce(baseState, s => {292 s.push(3)293 })294 expect("x" in nextState).toBeFalsy()295 })296297 if (useProxies) {298 it("throws when a non-numeric property is added", () => {299 expect(() => {300 produce([], d => {301 d.x = 3302 })303 }).toThrowErrorMatchingSnapshot()304 })305306 it("throws when a non-numeric property is deleted", () => {307 expect(() => {308 const baseState = []309 baseState.x = 7310 produce(baseState, d => {311 delete d.x312 })313 }).toThrowErrorMatchingSnapshot()314 })315 }316 })317

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 318–403why, one step back
318 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 back
404 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 back
408 const result = produce(base, draft => {
409 expect([...draft.keys()]).toEqual(["first", "second"])410 draft.set("third", Symbol())411 expect([...draft.keys()]).toEqual(["first", "second", "third"])412 })413 })414415 it("supports forEach", () => {416 const key1 = {prop: "val1"}417 const key2 = {prop: "val2"}418 const base = new Map([419 ["first", {id: 1, a: 1}],420 ["second", {id: 2, a: 1}],421 [key1, {id: 3, a: 1}],422 [key2, {id: 4, a: 1}]423 ])424 const result = produce(base, draft => {425 let sum1 = 0426 draft.forEach(({a}) => {427 sum1 += a428 })429 expect(sum1).toBe(4)430 let sum2 = 0431 draft.get("first").a = 10432 draft.get("second").a = 20433 draft.get(key1).a = 30434 draft.get(key2).a = 40435 draft.forEach(({a}) => {436 sum2 += a437 })438 expect(sum2).toBe(100)439 })440 expect(result).not.toBe(base)441 expect(base.get("first").a).toEqual(1)442 expect(base.get("second").a).toEqual(1)443 expect(base.get(key1).a).toEqual(1)444 expect(base.get(key2).a).toEqual(1)445 expect(result.get("first").a).toEqual(10)446 expect(result.get("second").a).toEqual(20)447 expect(result.get(key1).a).toEqual(30)448 expect(result.get(key2).a).toEqual(40)449 })450451 it("supports forEach mutation", () => {452 const base = new Map([453 ["first", {id: 1, a: 1}],454 ["second", {id: 2, a: 1}]455 ])456 const result = produce(base, draft => {457 draft.forEach(item => {458 item.a = 100459 })460 })461 expect(result).not.toBe(base)462 expect(result.get("first").a).toEqual(100)463 expect(result.get("second").a).toEqual(100)464 })465466 it("can assign by key", () => {467 const nextState = produce(baseState, s => {468 // Map.prototype.set should return the Map itself469 const res = s.aMap.set("force", true)

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

line 470why, one step back
470 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 back
471 })
472 expect(nextState).not.toBe(baseState)473 expect(nextState.aMap).not.toBe(baseState.aMap)474 expect(nextState.aMap.get("force")).toEqual(true)475 })476477 it("can assign by a non-primitive key", () => {478 const key = {prop: "val"}479 const value = {id: 1, a: 1}480 const base = new Map([[key, value]])481 const nextState = produce(base, s => {482 s.set(key, true)483 })484 expect(nextState).not.toBe(base)485 expect(base.get(key)).toEqual(value)486 expect(nextState.get(key)).toEqual(true)487 })488489 it("state stays the same if the the same item is assigned by key", () => {490 const nextState = produce(baseState, s => {491 s.aMap.set("jediTotal", 42)492 })493 expect(nextState).toBe(baseState)494 expect(nextState.aMap).toBe(baseState.aMap)495 })496497 it("returns 'size'", () => {498 const nextState = produce(baseState, s => {499 s.aMap.set("newKey", true)500 expect(s.aMap.size).toBe(baseState.aMap.size + 1)501 })502 expect(nextState).not.toBe(baseState)503 expect(nextState.aMap).not.toBe(baseState.aMap)504 expect(nextState.aMap.get("newKey")).toEqual(true)505 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)506 })507508 it("can use 'delete' to remove items", () => {509 const nextState = produce(baseState, s => {510 expect(s.aMap.has("jedi")).toBe(true)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 511why, one step back
511 expect(s.aMap.delete("jedi")).toBe(true)

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 512–555why, one step back
512 expect(s.aMap.has("jedi")).toBe(false)
513 })514 expect(nextState.aMap).not.toBe(baseState.aMap)515 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)516 expect(baseState.aMap.has("jedi")).toBe(true)517 expect(nextState.aMap.has("jedi")).toBe(false)518 })519520 it("can use 'clear' to remove items", () => {521 const nextState = produce(baseState, s => {522 expect(s.aMap.size).not.toBe(0)523 s.aMap.clear()524 expect(s.aMap.size).toBe(0)525 })526 expect(nextState.aMap).not.toBe(baseState.aMap)527 expect(baseState.aMap.size).not.toBe(0)528 expect(nextState.aMap.size).toBe(0)529 })530531 it("support 'has'", () => {532 const nextState = produce(baseState, s => {533 expect(s.aMap.has("newKey")).toBe(false)534 s.aMap.set("newKey", true)535 expect(s.aMap.has("newKey")).toBe(true)536 })537 expect(nextState).not.toBe(baseState)538 expect(nextState.aMap).not.toBe(baseState.aMap)539 expect(baseState.aMap.has("newKey")).toBe(false)540 expect(nextState.aMap.has("newKey")).toBe(true)541 })542543 it("supports nested maps", () => {544 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])545 const result = produce(base, draft => {546 draft.get("first").get("second").prop = "test1"547 })548 expect(result).not.toBe(base)549 expect(result.get("first")).not.toBe(base.get("first"))550 expect(result.get("first").get("second")).not.toBe(551 base.get("first").get("second")552 )553 expect(base.get("first").get("second").prop).toBe("test")554 expect(result.get("first").get("second").prop).toBe("test1")555 })

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 556–596why, one step back
556
557 it("treats void deletes as no-op", () => {558 const base = new Map([["x", 1]])559 const next = produce(base, d => {560 expect(d.delete("y")).toBe(false)561 })562 expect(next).toBe(base)563 })564565 it("revokes map proxies", () => {566 let m567 produce(baseState, s => {568 m = s.aMap569 })570 expect(() => m.get("x")).toThrow(571 "Cannot use a proxy that has been revoked"572 )573 expect(() => m.set("x", 3)).toThrow(574 "Cannot use a proxy that has been revoked"575 )576 })577578 it("does not draft map keys", () => {579 // anything else would be terribly confusing580 const key = {a: 1}581 const map = new Map([[key, 2]])582 const next = produce(map, d => {583 const dKey = Array.from(d.keys())[0]584 expect(isDraft(dKey)).toBe(false)585 expect(dKey).toBe(key)586 dKey.a += 1587 d.set(dKey, d.get(dKey) + 1)588 d.set(key, d.get(key) + 1)589 expect(d.get(key)).toBe(4)590 expect(key.a).toBe(2)591 })592 const entries = Array.from(next.entries())593 expect(entries).toEqual([[key, 4]])594 expect(entries[0][0]).toBe(key)595 expect(entries[0][0].a).toBe(2)596 })

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

lines 597–603why, one step back
597
598 it("does support instanceof Map", () => {599 const map = new Map()600 produce(map, d => {601 expect(d instanceof Map).toBeTruthy()602 })603 })

feat: general typing improvements for TS 3.7 and upMichel Weststratebefore adoptionf930ce1

lines 604–617why, one step back
604
605 it("handles clear correctly", () => {606 const map = new Map([607 ["a", 1],608 ["c", 3]609 ])610 const next = produce(map, draft => {611 draft.delete("a")612 draft.set("b", 2)613 draft.set("c", 4)614 draft.clear()615 })616 expect(next).toEqual(new Map())617 })

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 618–621why, one step back
618 })
619620 describe("set drafts", () => {621 it("supports iteration", () => {

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 622–625why, one step back
622 const base = new Set([
623 {id: 1, a: 1},624 {id: 2, a: 1}625 ])

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 626–638why, one step back
626 const findById = (set, id) => {
627 for (const item of set) {628 if (item.id === id) return item629 }630 return null631 }632 const result = produce(base, draft => {633 const obj1 = findById(draft, 1)634 const obj2 = findById(draft, 2)635 obj1.a = 2636 obj2.a = 2637 })638 expect(result).not.toBe(base)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 639–650why, one step back
639 expect(base).toEqual(
640 new Set([641 {id: 1, a: 1},642 {id: 2, a: 1}643 ])644 )645 expect(result).toEqual(646 new Set([647 {id: 1, a: 2},648 {id: 2, a: 2}649 ])650 )

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 651–653why, one step back
651 })
652653 it("supports 'entries'", () => {

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 654–657why, one step back
654 const base = new Set([
655 {id: 1, a: 1},656 {id: 2, a: 1}657 ])

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 658–671why, one step back
658 const findById = (set, id) => {
659 for (const [item1, item2] of set.entries()) {660 expect(item1).toBe(item2)661 if (item1.id === id) return item1662 }663 return null664 }665 const result = produce(base, draft => {666 const obj1 = findById(draft, 1)667 const obj2 = findById(draft, 2)668 obj1.a = 2669 obj2.a = 2670 })671 expect(result).not.toBe(base)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 672–683why, one step back
672 expect(base).toEqual(
673 new Set([674 {id: 1, a: 1},675 {id: 2, a: 1}676 ])677 )678 expect(result).toEqual(679 new Set([680 {id: 1, a: 2},681 {id: 2, a: 2}682 ])683 )

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 684–686why, one step back
684 })
685686 it("supports 'values'", () => {

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 687–690why, one step back
687 const base = new Set([
688 {id: 1, a: 1},689 {id: 2, a: 1}690 ])

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 691–703why, one step back
691 const findById = (set, id) => {
692 for (const item of set.values()) {693 if (item.id === id) return item694 }695 return null696 }697 const result = produce(base, draft => {698 const obj1 = findById(draft, 1)699 const obj2 = findById(draft, 2)700 obj1.a = 2701 obj2.a = 2702 })703 expect(result).not.toBe(base)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 704–715why, one step back
704 expect(base).toEqual(
705 new Set([706 {id: 1, a: 1},707 {id: 2, a: 1}708 ])709 )710 expect(result).toEqual(711 new Set([712 {id: 1, a: 2},713 {id: 2, a: 2}714 ])715 )

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 716–718why, one step back
716 })
717718 it("supports 'keys'", () => {

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 719–722why, one step back
719 const base = new Set([
720 {id: 1, a: 1},721 {id: 2, a: 1}722 ])

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 723–735why, one step back
723 const findById = (set, id) => {
724 for (const item of set.keys()) {725 if (item.id === id) return item726 }727 return null728 }729 const result = produce(base, draft => {730 const obj1 = findById(draft, 1)731 const obj2 = findById(draft, 2)732 obj1.a = 2733 obj2.a = 2734 })735 expect(result).not.toBe(base)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 736–747why, one step back
736 expect(base).toEqual(
737 new Set([738 {id: 1, a: 1},739 {id: 2, a: 1}740 ])741 )742 expect(result).toEqual(743 new Set([744 {id: 1, a: 2},745 {id: 2, a: 2}746 ])747 )

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 748–750why, one step back
748 })
749750 it("supports forEach with mutation after reads", () => {

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 751–754why, one step back
751 const base = new Set([
752 {id: 1, a: 1},753 {id: 2, a: 2}754 ])

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 755–768why, one step back
755 const result = produce(base, draft => {
756 let sum1 = 0757 draft.forEach(({a}) => {758 sum1 += a759 })760 expect(sum1).toBe(3)761 let sum2 = 0762 draft.forEach(item => {763 item.a += 10764 sum2 += item.a765 })766 expect(sum2).toBe(23)767 })768 expect(result).not.toBe(base)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 769–780why, one step back
769 expect(base).toEqual(
770 new Set([771 {id: 1, a: 1},772 {id: 2, a: 2}773 ])774 )775 expect(result).toEqual(776 new Set([777 {id: 1, a: 11},778 {id: 2, a: 12}779 ])780 )

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 781–794why, one step back
781 })
782783 it("state stays the same if the same item is added", () => {784 const nextState = produce(baseState, s => {785 s.aSet.add("Luke")786 })787 expect(nextState).toBe(baseState)788 expect(nextState.aSet).toBe(baseState.aSet)789 })790791 it("can add new items", () => {792 const nextState = produce(baseState, s => {793 // Set.prototype.set should return the Set itself794 const res = s.aSet.add("force")

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

line 795why, one step back
795 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 796–816why, one step back
796 })
797 expect(nextState).not.toBe(baseState)798 expect(nextState.aSet).not.toBe(baseState.aSet)799 expect(baseState.aSet.has("force")).toBe(false)800 expect(nextState.aSet.has("force")).toBe(true)801 })802803 it("returns 'size'", () => {804 const nextState = produce(baseState, s => {805 s.aSet.add("newKey")806 expect(s.aSet.size).toBe(baseState.aSet.size + 1)807 })808 expect(nextState).not.toBe(baseState)809 expect(nextState.aSet).not.toBe(baseState.aSet)810 expect(nextState.aSet.has("newKey")).toBe(true)811 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)812 })813814 it("can use 'delete' to remove items", () => {815 const nextState = produce(baseState, s => {816 expect(s.aSet.has("Luke")).toBe(true)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 817–818why, one step back
817 expect(s.aSet.delete("Luke")).toBe(true)
818 expect(s.aSet.delete("Luke")).toBe(false)

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 819–823why, one step back
819 expect(s.aSet.has("Luke")).toBe(false)
820 })821 expect(nextState.aSet).not.toBe(baseState.aSet)822 expect(baseState.aSet.has("Luke")).toBe(true)823 expect(nextState.aSet.has("Luke")).toBe(false)

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 824why, one step back
824 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 825–858why, one step back
825 })
826827 it("can use 'clear' to remove items", () => {828 const nextState = produce(baseState, s => {829 expect(s.aSet.size).not.toBe(0)830 s.aSet.clear()831 expect(s.aSet.size).toBe(0)832 })833 expect(nextState.aSet).not.toBe(baseState.aSet)834 expect(baseState.aSet.size).not.toBe(0)835 expect(nextState.aSet.size).toBe(0)836 })837838 it("supports 'has'", () => {839 const nextState = produce(baseState, s => {840 expect(s.aSet.has("newKey")).toBe(false)841 s.aSet.add("newKey")842 expect(s.aSet.has("newKey")).toBe(true)843 })844 expect(nextState).not.toBe(baseState)845 expect(nextState.aSet).not.toBe(baseState.aSet)846 expect(baseState.aSet.has("newKey")).toBe(false)847 expect(nextState.aSet.has("newKey")).toBe(true)848 })849850 it("supports nested sets", () => {851 const base = new Set([new Set(["Serenity"])])852 const result = produce(base, draft => {853 draft.forEach(nestedItem => nestedItem.add("Firefly"))854 })855 expect(result).not.toBe(base)856 expect(base).toEqual(new Set([new Set(["Serenity"])]))857 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))858 })

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 859–883why, one step back
859
860 it("supports has / delete on elements from the original", () => {861 const obj = {}862 const set = new Set([obj])863 const next = produce(set, d => {864 expect(d.has(obj)).toBe(true)865 d.add(3)866 expect(d.has(obj)).toBe(true)867 d.delete(obj)868 expect(d.has(obj)).toBe(false)869 })870 expect(next).toEqual(new Set([3]))871 })872873 it("revokes sets", () => {874 let m875 produce(baseState, s => {876 m = s.aSet877 })878 expect(() => m.has("x")).toThrow(879 "Cannot use a proxy that has been revoked"880 )881 expect(() => m.add("x")).toThrow(882 "Cannot use a proxy that has been revoked"883 )

fix: Map and Set instantions won't work on certain environments, fixes #502Michel Weststratebefore adoption9f4711a

lines 884–890why, one step back
884 })
885886 it("does support instanceof Set", () => {887 const set = new Set()888 produce(set, d => {889 expect(d instanceof Set).toBeTruthy()890 })

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

line 891why, one step back
891 })

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 892–893why, one step back
892 })
893

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 894–918why, one step back
894 it("supports `immerable` symbol on constructor", () => {
895 class One {}896 One[immerable] = true897 const baseState = new One()898 const nextState = produce(baseState, draft => {899 expect(draft).not.toBe(baseState)900 draft.foo = true901 })902 expect(nextState).not.toBe(baseState)903 expect(nextState.foo).toBeTruthy()904 })905906 it("preserves symbol properties", () => {907 const test = Symbol("test")908 const baseState = {[test]: true}909 const nextState = produce(baseState, s => {910 expect(s[test]).toBeTruthy()911 s.foo = true912 })913 expect(nextState).toEqual({914 [test]: true,915 foo: true916 })917 })918

chore: verify build during testMichel Weststratebefore adoptionef8990b

lines 919–941why, one step back
919 if (!global.USES_BUILD)
920 it("preserves non-enumerable properties", () => {921 const baseState = {}922 // Non-enumerable object property923 Object.defineProperty(baseState, "foo", {924 value: {a: 1},925 enumerable: false926 })927 // Non-enumerable primitive property928 Object.defineProperty(baseState, "bar", {929 value: 1,930 enumerable: false931 })932 const nextState = produce(baseState, s => {933 expect(s.foo).toBeTruthy()934 expect(isEnumerable(s, "foo")).toBeFalsy()935 s.bar++936 expect(isEnumerable(s, "foo")).toBeFalsy()937 s.foo.a++938 expect(isEnumerable(s, "foo")).toBeFalsy()939 })940 expect(nextState.foo).toBeTruthy()941 expect(isEnumerable(nextState, "foo")).toBeFalsy()

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 942–1133why, one step back
942 })
943944 it("throws on computed properties", () => {945 const baseState = {}946 Object.defineProperty(baseState, "foo", {947 get: () => {},948 enumerable: true949 })950 expect(() => {951 produce(baseState, s => {952 // Proxies only throw once a change is made.953 if (useProxies) {954 s.modified = true955 }956 })957 }).toThrowErrorMatchingSnapshot()958 })959960 it("allows inherited computed properties", () => {961 const proto = {}962 Object.defineProperty(proto, "foo", {963 get() {964 return this.bar965 },966 set(val) {967 this.bar = val968 }969 })970 const baseState = Object.create(proto)971 produce(baseState, s => {972 expect(s.bar).toBeUndefined()973 s.foo = {}974 expect(s.bar).toBeDefined()975 expect(s.foo).toBe(s.bar)976 })977 })978979 it("supports a base state with multiple references to an object", () => {980 const obj = {}981 const res = produce({a: obj, b: obj}, d => {982 // Two drafts are created for each occurrence of an object in the base state.983 expect(d.a).not.toBe(d.b)984 d.a.z = true985 expect(d.b.z).toBeUndefined()986 })987 expect(res.b).toBe(obj)988 expect(res.a).not.toBe(res.b)989 expect(res.a.z).toBeTruthy()990 })991992 // NOTE: Except the root draft.993 it("supports multiple references to any modified draft", () => {994 const next = produce({a: {b: 1}}, d => {995 d.a.b++996 d.b = d.a997 })998 expect(next.a).toBe(next.b)999 })10001001 it("can rename nested objects (no changes)", () => {1002 const nextState = produce({obj: {}}, s => {1003 s.foo = s.obj1004 delete s.obj1005 })1006 expect(nextState).toEqual({foo: {}})1007 })10081009 // Very similar to the test before, but the reused object has one1010 // property changed, one added, and one removed.1011 it("can rename nested objects (with changes)", () => {1012 const nextState = produce({obj: {a: 1, b: 1}}, s => {1013 s.obj.a = true // change1014 delete s.obj.b // delete1015 s.obj.c = true // add10161017 s.foo = s.obj1018 delete s.obj1019 })1020 expect(nextState).toEqual({foo: {a: true, c: true}})1021 })10221023 it("can nest a draft in a new object (no changes)", () => {1024 const baseState = {obj: {}}1025 const nextState = produce(baseState, s => {1026 s.foo = {bar: s.obj}1027 delete s.obj1028 })1029 expect(nextState.foo.bar).toBe(baseState.obj)1030 })10311032 it("can nest a modified draft in a new object", () => {1033 const nextState = produce({obj: {a: 1, b: 1}}, s => {1034 s.obj.a = true // change1035 delete s.obj.b // delete1036 s.obj.c = true // add10371038 s.foo = {bar: s.obj}1039 delete s.obj1040 })1041 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1042 })10431044 it("supports assigning undefined to an existing property", () => {1045 const nextState = produce(baseState, s => {1046 s.aProp = undefined1047 })1048 expect(nextState).not.toBe(baseState)1049 expect(nextState.aProp).toBe(undefined)1050 })10511052 it("supports assigning undefined to a new property", () => {1053 const baseState = {}1054 const nextState = produce(baseState, s => {1055 s.aProp = undefined1056 })1057 expect(nextState).not.toBe(baseState)1058 expect(nextState.aProp).toBe(undefined)1059 })10601061 // NOTE: ES5 drafts only protect existing properties when revoked.1062 it("revokes the draft once produce returns", () => {1063 const expectRevoked = (fn, shouldThrow = true) => {1064 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()1065 else expect(fn).not.toThrow()1066 }10671068 // Test object drafts:1069 let draft1070 produce({a: 1, b: 1}, s => {1071 draft = s1072 delete s.b1073 })10741075 // Access known property on object draft.1076 expectRevoked(() => {1077 draft.a1078 })10791080 // Assign known property on object draft.1081 expectRevoked(() => {1082 draft.a = true1083 })10841085 // Access unknown property on object draft.1086 expectRevoked(() => {1087 draft.z1088 }, useProxies)10891090 // Assign unknown property on object draft.1091 expectRevoked(() => {1092 draft.z = true1093 }, useProxies)10941095 // Test array drafts:1096 produce([1, 2], s => {1097 draft = s1098 s.pop()1099 })11001101 // Access known index of an array draft.1102 expectRevoked(() => {1103 draft[0]1104 })11051106 // Assign known index of an array draft.1107 expectRevoked(() => {1108 draft[0] = true1109 })11101111 // Access unknown index of an array draft.1112 expectRevoked(() => {1113 draft[1]1114 }, useProxies)11151116 // Assign unknown index of an array draft.1117 expectRevoked(() => {1118 draft[1] = true1119 }, useProxies)1120 })11211122 it("can access a child draft that was created before the draft was modified", () => {1123 produce({a: {}}, s => {1124 const before = s.a1125 s.b = 11126 expect(s.a).toBe(before)1127 })1128 })11291130 it("should reflect all changes made in the draft immediately", () => {1131 produce(baseState, draft => {1132 draft.anArray[0] = 51133 draft.anArray.unshift("test")

chore: verify build during testMichel Weststratebefore adoptionef8990b

lines 1134–1141why, one step back
1134 if (!global.USES_BUILD)
1135 expect(enumerableOnly(draft.anArray)).toEqual([1136 "test",1137 5,1138 2,1139 {c: 3},1140 11141 ])

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 1142–1393why, one step back
1142 draft.stuffz = "coffee"
1143 expect(draft.stuffz).toBe("coffee")1144 })1145 })11461147 if (useProxies)1148 it("throws when Object.defineProperty() is used on drafts", () => {1149 expect(() => {1150 produce({}, draft => {1151 Object.defineProperty(draft, "xx", {1152 enumerable: true,1153 writeable: true,1154 value: 21155 })1156 })1157 }).toThrowErrorMatchingSnapshot()1158 })11591160 it("should handle constructor correctly", () => {1161 const baseState = {1162 arr: new Array(),1163 obj: new Object()1164 }1165 const result = produce(baseState, draft => {1166 draft.arrConstructed = draft.arr.constructor(1)1167 draft.objConstructed = draft.obj.constructor(1)1168 })1169 expect(result.arrConstructed).toEqual(new Array().constructor(1))1170 expect(result.objConstructed).toEqual(new Object().constructor(1))1171 })11721173 it("should handle equality correctly - 1", () => {1174 const baseState = {1175 y: 3 / 0,1176 z: NaN1177 }1178 const nextState = produce(baseState, draft => {1179 draft.y = 4 / 01180 draft.z = NaN1181 })1182 expect(nextState).toBe(baseState)1183 })11841185 it("should handle equality correctly - 2", () => {1186 const baseState = {1187 x: -01188 }1189 const nextState = produce(baseState, draft => {1190 draft.x = +01191 })1192 expect(nextState).not.toBe(baseState)1193 expect(nextState).not.toEqual(baseState)1194 })11951196 // AKA: recursive produce calls1197 describe("nested producers", () => {1198 describe("when base state is not a draft", () => {1199 // This test ensures the global state used to manage proxies is1200 // never left in a corrupted state by a nested `produce` call.1201 it("never affects its parent producer implicitly", () => {1202 const base = {obj: {a: 1}}1203 const next = produce(base, draft => {1204 // Notice how `base.obj` is passed, not `draft.obj`1205 const obj2 = produce(base.obj, draft2 => {1206 draft2.a = 01207 })1208 expect(obj2.a).toBe(0)1209 expect(draft.obj.a).toBe(1) // effects should not be visible outside1210 })1211 expect(next).toBe(base)1212 })1213 })12141215 describe("when base state is a draft", () => {1216 it("always wraps the draft in a new draft", () => {1217 produce({}, parent => {1218 produce(parent, child => {1219 expect(child).not.toBe(parent)1220 expect(isDraft(child)).toBeTruthy()1221 expect(original(child)).toBe(parent)1222 })1223 })1224 })12251226 // Reported by: https://github.com/mweststrate/immer/issues/3431227 it("ensures each property is drafted", () => {1228 produce({a: {}, b: {}}, parent => {1229 parent.a // Access "a" but not "b"1230 produce(parent, child => {1231 child.c = 11232 expect(isDraft(child.a)).toBeTruthy()1233 expect(isDraft(child.b)).toBeTruthy()1234 })1235 })1236 })12371238 it("preserves any pending changes", () => {1239 produce({a: 1, b: 1, d: 1}, parent => {1240 parent.b = 21241 parent.c = 21242 delete parent.d1243 produce(parent, child => {1244 expect(child.a).toBe(1) // unchanged1245 expect(child.b).toBe(2) // changed1246 expect(child.c).toBe(2) // added1247 expect(child.d).toBeUndefined() // deleted1248 })1249 })1250 })1251 })12521253 describe("when base state contains a draft", () => {1254 it("wraps unowned draft with its own draft", () => {1255 produce({a: {}}, parent => {1256 produce({a: parent.a}, child => {1257 expect(child.a).not.toBe(parent.a)1258 expect(isDraft(child.a)).toBeTruthy()1259 expect(original(child.a)).toBe(parent.a)1260 })1261 })1262 })12631264 it("returns unowned draft if no changes were made", () => {1265 produce({a: {}}, parent => {1266 const result = produce({a: parent.a}, () => {})1267 expect(result.a).toBe(parent.a)1268 })1269 })12701271 it("clones the unowned draft when changes are made", () => {1272 produce({a: {}}, parent => {1273 const result = produce({a: parent.a}, child => {1274 child.a.b = 11275 })1276 expect(result.a).not.toBe(parent.a)1277 expect(result.a.b).toBe(1)1278 expect("b" in parent.a).toBeFalsy()1279 })1280 })12811282 // We cannot auto-freeze the result of a nested producer,1283 // because it may contain a draft from a parent producer.1284 it("never auto-freezes the result", () => {1285 produce({a: {}}, parent => {1286 const r = produce({a: parent.a}, child => {1287 child.b = 1 // Ensure a copy is returned.1288 })1289 expect(Object.isFrozen(r)).toBeFalsy()1290 })1291 })1292 })12931294 // "Upvalues" are variables from a parent scope.1295 it("does not finalize upvalue drafts", () => {1296 produce({a: {}, b: {}}, parent => {1297 expect(produce({}, () => parent)).toBe(parent)1298 parent.x // Ensure proxy not revoked.12991300 expect(produce({}, () => [parent])[0]).toBe(parent)1301 parent.x // Ensure proxy not revoked.13021303 expect(produce({}, () => parent.a)).toBe(parent.a)1304 parent.a.x // Ensure proxy not revoked.13051306 // Modified parent test1307 parent.c = 11308 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1309 parent.b.x // Ensure proxy not revoked.1310 })1311 })13121313 it("works with interweaved Immer instances", () => {1314 const options = {useProxies, autoFreeze}1315 const one = createPatchedImmer(options)1316 const two = createPatchedImmer(options)13171318 const base = {}1319 const result = one.produce(base, s1 =>1320 two.produce({s1}, s2 => {1321 expect(original(s2.s1)).toBe(s1)1322 s2.n = 11323 s2.s1 = one.produce({s2}, s3 => {1324 expect(original(s3.s2)).toBe(s2)1325 expect(original(s3.s2.s1)).toBe(s2.s1)1326 return s3.s2.s11327 })1328 })1329 )1330 expect(result.n).toBe(1)1331 expect(result.s1).toBe(base)1332 })1333 })13341335 if (useProxies)1336 it("throws when Object.setPrototypeOf() is used on a draft", () => {1337 produce({}, draft => {1338 expect(() =>1339 Object.setPrototypeOf(draft, Array)1340 ).toThrowErrorMatchingSnapshot()1341 })1342 })13431344 it("supports the 'in' operator", () => {1345 produce(baseState, draft => {1346 // Known property1347 expect("anArray" in draft).toBe(true)1348 expect(Reflect.has(draft, "anArray")).toBe(true)13491350 // Unknown property1351 expect("bla" in draft).toBe(false)1352 expect(Reflect.has(draft, "bla")).toBe(false)13531354 // Known index1355 expect(0 in draft.anArray).toBe(true)1356 expect("0" in draft.anArray).toBe(true)1357 expect(Reflect.has(draft.anArray, 0)).toBe(true)1358 expect(Reflect.has(draft.anArray, "0")).toBe(true)13591360 // Unknown index1361 expect(17 in draft.anArray).toBe(false)1362 expect("17" in draft.anArray).toBe(false)1363 expect(Reflect.has(draft.anArray, 17)).toBe(false)1364 expect(Reflect.has(draft.anArray, "17")).toBe(false)1365 })1366 })13671368 it("'this' should not be bound anymore - 1", () => {1369 const base = {x: 3}1370 const next1 = produce(base, function() {1371 expect(this).toBe(undefined)1372 })1373 })13741375 it("'this' should not be bound anymore - 2", () => {1376 const incrementor = produce(function() {1377 expect(this).toBe(undefined)1378 })1379 incrementor()1380 })13811382 it("should be possible to use dynamic bound this", () => {1383 const world = {1384 counter: {count: 1},1385 inc: produce(function(draft) {1386 expect(this).toBe(world)1387 draft.counter.count = this.counter.count + 11388 })1389 }13901391 expect(world.inc(world).counter.count).toBe(2)1392 })1393

Cleanup. Don't recurse into frozen data structuresMichel Weststratebefore adoptiond32cb97

lines 1394–1411why, one step back
1394 it("doesnt recurse into frozen structures if external data is frozen", () => {
1395 const frozen = {}1396 Object.defineProperty(frozen, "x", {1397 get() {1398 throw "oops"1399 },1400 enumerable: true,1401 configurable: true1402 })1403 Object.freeze(frozen)14041405 expect(() => {1406 produce({}, d => {1407 d.x = frozen1408 })1409 }).not.toThrow()1410 })1411

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 1412–1443why, one step back
1412 // See here: https://github.com/mweststrate/immer/issues/89
1413 it("supports the spread operator", () => {1414 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1415 const result = produce(base, draft => {1416 draft.foo = {x: 1, ...draft.foo, y: 1}1417 draft.bar = [1, ...draft.bar, 1]1418 })1419 expect(result).toEqual({1420 foo: {x: 0, y: 1},1421 bar: [1, 0, 0, 1]1422 })1423 })14241425 it("processes with lodash.set", () => {1426 const base = [{id: 1, a: 1}]1427 const result = produce(base, draft => {1428 lodash.set(draft, "[0].a", 2)1429 })1430 expect(base[0].a).toEqual(1)1431 expect(result[0].a).toEqual(2)1432 })14331434 it("processes with lodash.find", () => {1435 const base = [{id: 1, a: 1}]1436 const result = produce(base, draft => {1437 const obj1 = lodash.find(draft, {id: 1})1438 lodash.set(obj1, "a", 2)1439 })1440 expect(base[0].a).toEqual(1)1441 expect(result[0].a).toEqual(2)1442 })1443

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 1444–1457why, one step back
1444 it("does not draft external data", () => {
1445 const externalData = {x: 3}1446 const base = {}1447 const next = produce(base, draft => {1448 // potentially, we *could* draft external data automatically, but only if those statements are not switched...1449 draft.y = externalData1450 draft.y.x += 11451 externalData.x += 11452 })1453 expect(next).toEqual({y: {x: 5}})1454 expect(externalData.x).toBe(5)1455 expect(next.y).toBe(externalData)1456 })1457

chore: added test for #491Michel Weststratebefore adoption788dc03

lines 1458–1472why, one step back
1458 it("does not create new state unnecessary, #491", () => {
1459 const a = {highlight: true}1460 const next1 = produce(a, draft => {1461 draft.highlight = false1462 draft.highlight = true1463 })1464 // See explanation in issue1465 expect(next1).not.toBe(a)14661467 const next2 = produce(a, draft => {1468 draft.highlight = true1469 })1470 expect(next2).toBe(a)1471 })1472

test: tried to reproduce #469Michel Weststratebefore adoptione504e0b

line 1473why, one step back
1473 autoFreeze &&

chore: add test for #462Michel Weststratebefore adoptionce6a3c2

lines 1474–1491why, one step back
1474 test.skip("issue #462 - frozen", () => {
1475 var origin = {1476 a: {1477 value: "no"1478 },1479 b: {1480 value: "no"1481 }1482 }1483 var im = produce(origin, origin => {1484 origin.a.value = "im"1485 })1486 expect(() => (origin.b.value = "yes")).toThrow() // should throw!1487 // to prevent this...:1488 // expect(im.b.value).toBe('no');1489 })14901491 autoFreeze &&

test: tried to reproduce #469Michel Weststratebefore adoptione504e0b

lines 1492–1509why, one step back
1492 test("issue #469, state not frozen", () => {
1493 const project = produce(1494 {1495 id: 1,1496 tracks: [{id: 1}]1497 },1498 () => {}1499 )15001501 expect(() => {1502 project.id = 2 // Does not throw error1503 }).toThrowError("Cannot assign to read only property 'id'")15041505 expect(() => {1506 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1507 }).toThrowError("Cannot assign to read only property 'id'")1508 })1509

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 1510–1767why, one step back
1510 describe("recipe functions", () => {
1511 it("can return a new object", () => {1512 const base = {x: 3}1513 const res = produce(base, d => {1514 return {x: d.x + 1}1515 })1516 expect(res).not.toBe(base)1517 expect(res).toEqual({x: 4})1518 })15191520 it("can return the draft", () => {1521 const base = {x: 3}1522 const res = produce(base, d => {1523 d.x = 41524 return d1525 })1526 expect(res).not.toBe(base)1527 expect(res).toEqual({x: 4})1528 })15291530 it("can return an unmodified child draft", () => {1531 const base = {a: {}}1532 const res = produce(base, d => {1533 return d.a1534 })1535 expect(res).toBe(base.a)1536 })15371538 // TODO: Avoid throwing if only the child draft was modified.1539 it("cannot return a modified child draft", () => {1540 const base = {a: {}}1541 expect(() => {1542 produce(base, d => {1543 d.a.b = 11544 return d.a1545 })1546 }).toThrowErrorMatchingSnapshot()1547 })15481549 it("can return a frozen object", () => {1550 const res = deepFreeze([{x: 3}])1551 expect(produce({}, () => res)).toBe(res)1552 })15531554 it("can return an object with two references to another object", () => {1555 const next = produce({}, d => {1556 const obj = {}1557 return {obj, arr: [obj]}1558 })1559 expect(next.obj).toBe(next.arr[0])1560 })15611562 it("can return an object with two references to an unmodified draft", () => {1563 const base = {a: {}}1564 const next = produce(base, d => {1565 return [d.a, d.a]1566 })1567 expect(next[0]).toBe(base.a)1568 expect(next[0]).toBe(next[1])1569 })15701571 it("cannot return an object that references itself", () => {1572 const res = {}1573 res.self = res1574 expect(() => {1575 produce(res, () => res.self)1576 }).toThrowErrorMatchingSnapshot()1577 })1578 })15791580 describe("async recipe function", () => {1581 it("can modify the draft", () => {1582 const base = {a: 0, b: 0}1583 return produce(base, async d => {1584 d.a = 11585 await Promise.resolve()1586 d.b = 11587 }).then(res => {1588 expect(res).not.toBe(base)1589 expect(res).toEqual({a: 1, b: 1})1590 })1591 })15921593 it("works with rejected promises", () => {1594 let draft1595 const base = {a: 0, b: 0}1596 const err = new Error("passed")1597 return produce(base, d => {1598 draft = d1599 draft.b = 11600 return Promise.reject(err)1601 }).then(1602 () => {1603 throw "failed"1604 },1605 e => {1606 expect(e).toBe(err)1607 expect(() => draft.a).toThrowErrorMatchingSnapshot()1608 }1609 )1610 })16111612 it("supports recursive produce calls after await", () => {1613 const base = {obj: {k: 1}}1614 return produce(base, d => {1615 const obj = d.obj1616 delete d.obj1617 return Promise.resolve().then(() => {1618 d.a = produce({}, d => {1619 d.b = obj // Assign a draft owned by the parent scope.1620 })16211622 // Auto-freezing is prevented when an unowned draft exists.1623 expect(Object.isFrozen(d.a)).toBeFalsy()16241625 // Ensure `obj` is not revoked.1626 obj.c = 11627 })1628 }).then(res => {1629 expect(res).not.toBe(base)1630 expect(res).toEqual({1631 a: {b: {k: 1, c: 1}}1632 })1633 })1634 })1635 })16361637 it("throws when the draft is modified and another object is returned", () => {1638 const base = {x: 3}1639 expect(() => {1640 produce(base, draft => {1641 draft.x = 41642 return {x: 5}1643 })1644 }).toThrowErrorMatchingSnapshot()1645 })16461647 it("should fix #117 - 1", () => {1648 const reducer = (state, action) =>1649 produce(state, draft => {1650 switch (action.type) {1651 case "SET_STARTING_DOTS":1652 return draft.availableStartingDots.map(a => a)1653 default:1654 break1655 }1656 })1657 const base = {1658 availableStartingDots: [1659 {dots: 4, count: 1},1660 {dots: 3, count: 2},1661 {dots: 2, count: 3},1662 {dots: 1, count: 4}1663 ]1664 }1665 const next = reducer(base, {type: "SET_STARTING_DOTS"})1666 expect(next).toEqual(base.availableStartingDots)1667 expect(next).not.toBe(base.availableStartingDots)1668 })16691670 it("should fix #117 - 2", () => {1671 const reducer = (state, action) =>1672 produce(state, draft => {1673 switch (action.type) {1674 case "SET_STARTING_DOTS":1675 return {1676 dots: draft.availableStartingDots.map(a => a)1677 }1678 default:1679 break1680 }1681 })1682 const base = {1683 availableStartingDots: [1684 {dots: 4, count: 1},1685 {dots: 3, count: 2},1686 {dots: 2, count: 3},1687 {dots: 1, count: 4}1688 ]1689 }1690 const next = reducer(base, {type: "SET_STARTING_DOTS"})1691 expect(next).toEqual({dots: base.availableStartingDots})1692 })16931694 it("cannot always detect noop assignments - 0", () => {1695 const baseState = {x: {y: 3}}1696 const nextState = produce(baseState, d => {1697 const a = d.x1698 d.x = a1699 })1700 expect(nextState).toBe(baseState)1701 })17021703 it("cannot always detect noop assignments - 1", () => {1704 const baseState = {x: {y: 3}}1705 const nextState = produce(baseState, d => {1706 const a = d.x1707 d.x = 41708 d.x = a1709 })1710 // Ideally, this should actually be the same instances1711 // but this would be pretty expensive to detect,1712 // so we don't atm1713 expect(nextState).not.toBe(baseState)1714 })17151716 it("cannot always detect noop assignments - 2", () => {1717 const baseState = {x: {y: 3}}1718 const nextState = produce(baseState, d => {1719 const a = d.x1720 const stuff = a.y + 31721 d.x = 41722 d.x = a1723 })1724 // Ideally, this should actually be the same instances1725 // but this would be pretty expensive to detect,1726 // so we don't atm1727 expect(nextState).not.toBe(baseState)1728 })17291730 it("cannot always detect noop assignments - 3", () => {1731 const baseState = {x: 3}1732 const nextState = produce(baseState, d => {1733 d.x = 31734 })1735 expect(nextState).toBe(baseState)1736 })17371738 it("cannot always detect noop assignments - 4", () => {1739 const baseState = {x: 3}1740 const nextState = produce(baseState, d => {1741 d.x = 41742 d.x = 31743 })1744 // Ideally, this should actually be the same instances1745 // but this would be pretty expensive to detect,1746 // so we don't atm1747 expect(nextState).not.toBe(baseState)1748 })17491750 it("cannot produce undefined by returning undefined", () => {1751 const base = 31752 expect(produce(base, () => 4)).toBe(4)1753 expect(produce(base, () => null)).toBe(null)1754 expect(produce(base, () => undefined)).toBe(3)1755 expect(produce(base, () => {})).toBe(3)1756 expect(produce(base, () => nothing)).toBe(undefined)17571758 expect(produce({}, () => undefined)).toEqual({})1759 expect(produce({}, () => nothing)).toBe(undefined)1760 expect(produce(3, () => nothing)).toBe(undefined)17611762 expect(produce(() => undefined)({})).toEqual({})1763 expect(produce(() => nothing)({})).toBe(undefined)1764 expect(produce(() => nothing)(3)).toBe(undefined)1765 })17661767 describe("base state type", () => {

chore: verify build during testMichel Weststratebefore adoptionef8990b

line 1768why, one step back
1768 if (!global.USES_BUILD) testObjectTypes(produce)

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 1769–1781why, one step back
1769 testLiteralTypes(produce)
1770 })17711772 afterEach(() => {1773 expect(baseState).toBe(origBaseState)1774 expect(baseState).toEqual(createBaseState())1775 })17761777 class Foo {}1778 function createBaseState() {1779 const data = {1780 anInstance: new Foo(),1781 anArray: [3, 2, {c: 3}, 1],

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 1782–1793why, one step back
1782 aMap: new Map([
1783 ["jedi", {name: "Luke", skill: 10}],1784 ["jediTotal", 42],1785 ["force", "these aren't the droids you're looking for"]1786 ]),1787 aSet: new Set([1788 "Luke",1789 42,1790 {1791 jedi: "Yoda"1792 }1793 ]),

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 1794–1805why, one step back
1794 aProp: "hi",
1795 anObject: {1796 nested: {1797 yummie: true1798 },1799 coffee: false1800 }1801 }1802 return autoFreeze ? deepFreeze(data) : data1803 }1804 })1805

fix: Fixed issue where drafts from nested producers were frozen. Fixes #522, #524Michel Weststratebefore adoptionacc5e54

lines 1806–1899why, one step back
1806 it(`works with spread #524 - ${name}`, () => {
1807 const state = {1808 level1: {1809 level2: {1810 level3: "data"1811 }1812 }1813 }18141815 const nextState = produce(state, draft => {1816 return {...draft}1817 })1818 const nextState1 = produce(state, draft => {1819 const newLevel1 = produce(draft.level1, level1Draft => {1820 return {...level1Draft}1821 })1822 draft.level1 = newLevel11823 })18241825 const nextState2 = produce(state, draft => {1826 const newLevel1 = produce(draft.level1, level1Draft => {1827 return {...level1Draft}1828 })1829 return {1830 level1: newLevel11831 }1832 })18331834 const nextState3 = produce(state, draft => {1835 const newLevel1 = produce(draft.level1, level1Draft => {1836 return Object.assign({}, level1Draft)1837 })1838 return Object.assign(draft, {1839 level1: newLevel11840 })1841 })18421843 const expected = {level1: {level2: {level3: "data"}}}1844 expect(nextState1).toEqual(expected)1845 expect(nextState2).toEqual(expected)1846 expect(nextState3).toEqual(expected)1847 })18481849 it(`Something with nested producers #522 ${name}`, () => {1850 function initialStateFactory() {1851 return {1852 substate: {1853 array: [1854 {id: "id1", value: 0},1855 {id: "id2", value: 0}1856 ]1857 },1858 array: [1859 {id: "id1", value: 0},1860 {id: "id2", value: 0}1861 ]1862 }1863 }18641865 const globalProducer = produce(draft => {1866 draft.substate = subProducer(draft.substate)1867 draft.array = arrayProducer(draft.array)1868 }, initialStateFactory())18691870 const subProducer = produce(draftSubState => {1871 draftSubState.array = arrayProducer(draftSubState.array)1872 })18731874 const arrayProducer = produce(draftArray => {1875 draftArray[0].value += 51876 })18771878 {1879 const state = globalProducer(undefined)1880 expect(state.array[0].value).toBe(5)1881 expect(state.array.length).toBe(2)1882 expect(state.array[1]).toMatchObject({1883 id: "id2",1884 value: 01885 })1886 }18871888 {1889 const state = globalProducer(undefined)1890 expect(state.substate.array[0].value).toBe(5)1891 expect(state.substate.array.length).toBe(2)1892 expect(state.substate.array[1]).toMatchObject({1893 id: "id2",1894 value: 01895 })1896 expect(state.substate.array).toMatchObject(state.array)1897 }1898 })1899

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 1900–1937why, one step back
1900 describe(`isDraft - ${name}`, () => {
1901 it("returns true for object drafts", () => {1902 produce({}, state => {1903 expect(isDraft(state)).toBeTruthy()1904 })1905 })1906 it("returns true for array drafts", () => {1907 produce([], state => {1908 expect(isDraft(state)).toBeTruthy()1909 })1910 })1911 it("returns true for objects nested in object drafts", () => {1912 produce({a: {b: {}}}, state => {1913 expect(isDraft(state.a)).toBeTruthy()1914 expect(isDraft(state.a.b)).toBeTruthy()1915 })1916 })1917 it("returns false for new objects added to a draft", () => {1918 produce({}, state => {1919 state.a = {}1920 expect(isDraft(state.a)).toBeFalsy()1921 })1922 })1923 it("returns false for objects returned by the producer", () => {1924 const object = produce(null, Object.create)1925 expect(isDraft(object)).toBeFalsy()1926 })1927 it("returns false for arrays returned by the producer", () => {1928 const array = produce(null, _ => [])1929 expect(isDraft(array)).toBeFalsy()1930 })1931 it("returns false for object drafts returned by the producer", () => {1932 const object = produce({}, state => state)1933 expect(isDraft(object)).toBeFalsy()1934 })1935 it("returns false for array drafts returned by the producer", () => {1936 const array = produce([], state => state)1937 expect(isDraft(array)).toBeFalsy()

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 1938–1946why, one step back
1938 })
1939 })19401941 describe(`complex nesting map / set / object`, () => {1942 const a = {a: 1}1943 const b = {b: 2}1944 const c = {c: 3}1945 const set1 = new Set([a, b])1946 const set2 = new Set([c])

feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8

lines 1947–1950why, one step back
1947 const map = new Map([
1948 ["set1", set1],1949 ["set2", set2]1950 ])

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 1951–1999why, one step back
1951 const base = {map}
19521953 function first(set) {1954 return Array.from(set.values())[0]1955 }19561957 function second(set) {1958 return Array.from(set.values())[1]1959 }19601961 test(`modify deep object`, () => {1962 const [res, patches] = produceWithPatches(base, draft => {1963 const v = first(draft.map.get("set1"))1964 expect(original(v)).toBe(a)1965 expect(v).toEqual(a)1966 expect(v).not.toBe(a)1967 v.a++1968 })1969 expect(res).toMatchSnapshot()1970 expect(patches).toMatchSnapshot()1971 expect(a.a).toBe(1)1972 expect(base.map.get("set1")).toBe(set1)1973 expect(first(base.map.get("set1"))).toBe(a)1974 expect(res).not.toBe(base)1975 expect(res.map).not.toBe(base.map)1976 expect(res.map.get("set1")).not.toBe(base.map.get("set1"))1977 expect(second(base.map.get("set1"))).toBe(b)1978 expect(base.map.get("set2")).toBe(set2)1979 expect(first(res.map.get("set1"))).toEqual({a: 2})1980 })19811982 test(`modify deep object - keep value`, () => {1983 const [res, patches] = produceWithPatches(base, draft => {1984 const v = first(draft.map.get("set1"))1985 expect(original(v)).toBe(a)1986 expect(v).toEqual(a)1987 expect(v).not.toBe(a)1988 v.a = 1 // same value1989 })1990 expect(a.a).toBe(1)1991 expect(base.map.get("set1")).toBe(set1)1992 expect(first(base.map.get("set1"))).toBe(a)1993 expect(res).toBe(base)1994 expect(res.map).toBe(base.map)1995 expect(res.map.get("set1")).toBe(base.map.get("set1"))1996 expect(first(res.map.get("set1"))).toBe(a)1997 expect(second(base.map.get("set1"))).toBe(b)1998 expect(base.map.get("set2")).toBe(set2)1999 expect(patches.length).toBe(0)

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 2000–2003why, one step back
2000 })

The first 2,000 of 2,120 lines.