base.js
This file
Path
__tests__/base.js
1,780 lines · 48.1 KiB · JavaScript
Last changed by
fixed most testsMichel Weststratebefore adoption385c0a4
History of this fileTake it
The walk stopped after 200 commits: lines older than 66e51e1 point at it.
feat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
line 1why, one step back1"use strict"feat: limited class supportaleclarsonbefore adoption9877d64
line 2why, one step back2import {Immer, nothing, original, isDraft, immerable} from "../src/index"feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 3why, one step back3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/common"feat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
lines 4–9why, one step back4import deepFreeze from "deep-freeze"5import cloneDeep from "lodash.clonedeep"6import * as lodash from "lodash"78jest.setTimeout(1000)9chore: improve more testsaleclarsonbefore adoption4f59b12
line 10why, one step back10test("immer should have no dependencies", () => {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 11why, one step back11 expect(require("../package.json").dependencies).toBeUndefined()chore: improve more testsaleclarsonbefore adoption4f59b12
line 12why, one step back12})style: use tabsuse-tabsbefore adoptiona9c0fd0
line 13why, one step back13feat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
lines 14–19why, one step back14runBaseTest("proxy (no freeze)", true, false)15runBaseTest("proxy (autofreeze)", true, true)16runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)17runBaseTest("es5 (no freeze)", false, false)18runBaseTest("es5 (autofreeze)", false, true)19runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)style: use tabsuse-tabsbefore adoptiona9c0fd0
line 20why, one step back20test: improve tests with Immer classaleclarsonbefore adoptionddc9b40
line 21why, one step back21function runBaseTest(name, useProxies, autoFreeze, useListener) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 22why, one step back22 const listener = useListener ? function() {} : undefinedfeat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 23why, one step back23 const {produce, produceWithPatches} = createPatchedImmer({style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 24–33why, one step back24 useProxies,25 autoFreeze26 })2728 // When `useListener` is true, append a function to the arguments of every29 // uncurried `produce` call in every test. This makes tests easier to read.30 function createPatchedImmer(options) {31 const immer = new Immer(options)3233 const {produce} = immerfeat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 34–35why, one step back34 immer.produce = function(...args) {35 return typeof args[1] === "function" && args.length < 3style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 36–37why, one step back36 ? produce(...args, listener)37 : produce(...args)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 38why, one step back38 }style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 39–302why, one step back3940 return immer41 }4243 describe(`base functionality - ${name}`, () => {44 let baseState45 let origBaseState4647 beforeEach(() => {48 origBaseState = baseState = createBaseState()49 })5051 it("returns the original state when no changes are made", () => {52 const nextState = produce(baseState, s => {53 expect(s.aProp).toBe("hi")54 expect(s.anObject.nested).toMatchObject({yummie: true})55 })56 expect(nextState).toBe(baseState)57 })5859 it("does structural sharing", () => {60 const random = Math.random()61 const nextState = produce(baseState, s => {62 s.aProp = random63 })64 expect(nextState).not.toBe(baseState)65 expect(nextState.aProp).toBe(random)66 expect(nextState.nested).toBe(baseState.nested)67 })6869 it("deep change bubbles up", () => {70 const nextState = produce(baseState, s => {71 s.anObject.nested.yummie = false72 })73 expect(nextState).not.toBe(baseState)74 expect(nextState.anObject).not.toBe(baseState.anObject)75 expect(baseState.anObject.nested.yummie).toBe(true)76 expect(nextState.anObject.nested.yummie).toBe(false)77 expect(nextState.anArray).toBe(baseState.anArray)78 })7980 it("can add props", () => {81 const nextState = produce(baseState, s => {82 s.anObject.cookie = {tasty: true}83 })84 expect(nextState).not.toBe(baseState)85 expect(nextState.anObject).not.toBe(baseState.anObject)86 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)87 expect(nextState.anObject.cookie).toEqual({tasty: true})88 })8990 it("can delete props", () => {91 const nextState = produce(baseState, s => {92 delete s.anObject.nested93 })94 expect(nextState).not.toBe(baseState)95 expect(nextState.anObject).not.toBe(baseState.anObject)96 expect(nextState.anObject.nested).toBe(undefined)97 })9899 // Found by: https://github.com/mweststrate/immer/pull/267100 it("can delete props added in the producer", () => {101 const nextState = produce(baseState, s => {102 s.anObject.test = true103 delete s.anObject.test104 })105 if (useProxies) {106 expect(nextState).not.toBe(baseState)107 expect(nextState).toEqual(baseState)108 } else {109 // The copy is avoided in ES5.110 expect(nextState).toBe(baseState)111 }112 })113114 // Found by: https://github.com/mweststrate/immer/issues/328115 it("can set a property that was just deleted", () => {116 const baseState = {a: 1}117 const nextState = produce(baseState, s => {118 delete s.a119 s.a = 2120 })121 expect(nextState.a).toBe(2)122 })123124 it("can set a property to its original value after deleting it", () => {125 const baseState = {a: {b: 1}}126 const nextState = produce(baseState, s => {127 const a = s.a128 delete s.a129 s.a = a130 })131 if (useProxies) {132 expect(nextState).not.toBe(baseState)133 expect(nextState).toEqual(baseState)134 } else {135 // The copy is avoided in ES5.136 expect(nextState).toBe(baseState)137 }138 })139140 it("can get property descriptors", () => {141 const getDescriptor = Object.getOwnPropertyDescriptor142 const baseState = deepFreeze([{a: 1}])143 produce(baseState, arr => {144 const obj = arr[0]145 const desc = {146 configurable: true,147 enumerable: true,148 ...(useProxies && {writable: true})149 }150151 // Known property152 expect(getDescriptor(obj, "a")).toMatchObject(desc)153 expect(getDescriptor(arr, 0)).toMatchObject(desc)154155 // Deleted property156 delete obj.a157 arr.pop()158 expect(getDescriptor(obj, "a")).toBeUndefined()159 expect(getDescriptor(arr, 0)).toBeUndefined()160161 // Unknown property162 expect(getDescriptor(obj, "b")).toBeUndefined()163 expect(getDescriptor(arr, 100)).toBeUndefined()164165 // Added property166 obj.b = 2167 arr[100] = 1168 expect(getDescriptor(obj, "b")).toBeDefined()169 expect(getDescriptor(arr, 100)).toBeDefined()170 })171 })172173 describe("array drafts", () => {174 it("supports Array.isArray()", () => {175 const nextState = produce(baseState, s => {176 expect(Array.isArray(s.anArray)).toBeTruthy()177 s.anArray.push(1)178 })179 expect(Array.isArray(nextState.anArray)).toBeTruthy()180 })181182 it("supports index access", () => {183 const value = baseState.anArray[0]184 const nextState = produce(baseState, s => {185 expect(s.anArray[0]).toBe(value)186 })187 expect(nextState).toBe(baseState)188 })189190 it("supports iteration", () => {191 const base = [{id: 1, a: 1}, {id: 2, a: 1}]192 const findById = (collection, id) => {193 for (const item of collection) {194 if (item.id === id) return item195 }196 return null197 }198 const result = produce(base, draft => {199 const obj1 = findById(draft, 1)200 const obj2 = findById(draft, 2)201 obj1.a = 2202 obj2.a = 2203 })204 expect(result[0].a).toEqual(2)205 expect(result[1].a).toEqual(2)206 })207208 it("can assign an index via bracket notation", () => {209 const nextState = produce(baseState, s => {210 s.anArray[3] = true211 })212 expect(nextState).not.toBe(baseState)213 expect(nextState.anArray).not.toBe(baseState.anArray)214 expect(nextState.anArray[3]).toEqual(true)215 })216217 it("can use splice() to both add and remove items", () => {218 const nextState = produce(baseState, s => {219 s.anArray.splice(1, 1, "a", "b")220 })221 expect(nextState.anArray).not.toBe(baseState.anArray)222 expect(nextState.anArray[1]).toBe("a")223 expect(nextState.anArray[2]).toBe("b")224 })225226 it("can truncate via the length property", () => {227 const baseLength = baseState.anArray.length228 const nextState = produce(baseState, s => {229 s.anArray.length = baseLength - 1230 })231 expect(nextState.anArray).not.toBe(baseState.anArray)232 expect(nextState.anArray.length).toBe(baseLength - 1)233 })234235 it("can extend via the length property", () => {236 const baseLength = baseState.anArray.length237 const nextState = produce(baseState, s => {238 s.anArray.length = baseLength + 1239 })240 expect(nextState.anArray).not.toBe(baseState.anArray)241 expect(nextState.anArray.length).toBe(baseLength + 1)242 })243244 // Reported here: https://github.com/mweststrate/immer/issues/116245 it("can pop then push", () => {246 const nextState = produce([1, 2, 3], s => {247 s.pop()248 s.push(100)249 })250 expect(nextState).toEqual([1, 2, 100])251 })252253 it("can be sorted", () => {254 const baseState = [3, 1, 2]255 const nextState = produce(baseState, s => {256 s.sort()257 })258 expect(nextState).not.toBe(baseState)259 expect(nextState).toEqual([1, 2, 3])260 })261262 it("supports modifying nested objects", () => {263 const baseState = [{a: 1}, {}]264 const nextState = produce(baseState, s => {265 s[0].a++266 s[1].a = 0267 })268 expect(nextState).not.toBe(baseState)269 expect(nextState[0].a).toBe(2)270 expect(nextState[1].a).toBe(0)271 })272273 it("never preserves non-numeric properties", () => {274 const baseState = []275 baseState.x = 7276 const nextState = produce(baseState, s => {277 s.push(3)278 })279 expect("x" in nextState).toBeFalsy()280 })281282 if (useProxies) {283 it("throws when a non-numeric property is added", () => {284 expect(() => {285 produce([], d => {286 d.x = 3287 })288 }).toThrowErrorMatchingSnapshot()289 })290291 it("throws when a non-numeric property is deleted", () => {292 expect(() => {293 const baseState = []294 baseState.x = 7295 produce(baseState, d => {296 delete d.x297 })298 }).toThrowErrorMatchingSnapshot()299 })300 }301 })302feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 303–321why, one step back303 describe("map drafts", () => {304 it("supports key access", () => {305 const value = baseState.aMap.get("jedi")306 const nextState = produce(baseState, s => {307 expect(s.aMap.get("jedi")).toEqual(value)308 })309 expect(nextState).toBe(baseState)310 })311312 it("supports key access for non-primitive keys", () => {313 const key = {prop: "val"}314 const base = new Map([[key, {id: 1, a: 1}]])315 const value = base.get(key)316 const nextState = produce(base, s => {317 expect(s.get(key)).toEqual(value)318 })319 expect(nextState).toBe(base)320 })321fixed most testsMichel Weststratebefore adoption385c0a4
line 322why, one step back322 it("supports iteration", () => {feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 323–343why, one step back323 const base = new Map([324 ["first", {id: 1, a: 1}],325 ["second", {id: 2, a: 1}]326 ])327 const findById = (map, id) => {328 for (const [, item] of map) {329 if (item.id === id) return item330 }331 return null332 }333 const result = produce(base, draft => {334 const obj1 = findById(draft, 1)335 const obj2 = findById(draft, 2)336 obj1.a = 2337 obj2.a = 2338 })339 expect(result).not.toBe(base)340 expect(result.get("first").a).toEqual(2)341 expect(result.get("second").a).toEqual(2)342 })343fixed most testsMichel Weststratebefore adoption385c0a4
line 344why, one step back344 it("supports 'entries'", () => {feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 345–365why, one step back345 const base = new Map([346 ["first", {id: 1, a: 1}],347 ["second", {id: 2, a: 1}]348 ])349 const findById = (map, id) => {350 for (const [, item] of map.entries()) {351 if (item.id === id) return item352 }353 return null354 }355 const result = produce(base, draft => {356 const obj1 = findById(draft, 1)357 const obj2 = findById(draft, 2)358 obj1.a = 2359 obj2.a = 2360 })361 expect(result).not.toBe(base)362 expect(result.get("first").a).toEqual(2)363 expect(result.get("second").a).toEqual(2)364 })365fixed most testsMichel Weststratebefore adoption385c0a4
line 366why, one step back366 it("supports 'values'", () => {feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 367–492why, one step back367 const base = new Map([368 ["first", {id: 1, a: 1}],369 ["second", {id: 2, a: 1}]370 ])371 const findById = (map, id) => {372 for (const item of map.values()) {373 if (item.id === id) return item374 }375 return null376 }377 const result = produce(base, draft => {378 const obj1 = findById(draft, 1)379 const obj2 = findById(draft, 2)380 obj1.a = 2381 obj2.a = 2382 })383 expect(result).not.toBe(base)384 expect(result.get("first").a).toEqual(2)385 expect(result.get("second").a).toEqual(2)386 })387388 it("supports 'keys", () => {389 const base = new Map([["first", Symbol()], ["second", Symbol()]])390 const result = produce(base, draft => {391 expect([...draft.keys()]).toEqual(["first", "second"])392 draft.set("third", Symbol())393 expect([...draft.keys()]).toEqual(["first", "second", "third"])394 })395 })396397 it("supports forEach", () => {398 const key1 = {prop: "val1"}399 const key2 = {prop: "val2"}400 const base = new Map([401 ["first", {id: 1, a: 1}],402 ["second", {id: 2, a: 1}],403 [key1, {id: 3, a: 1}],404 [key2, {id: 4, a: 1}]405 ])406 const result = produce(base, draft => {407 let sum1 = 0408 draft.forEach(({a}) => {409 sum1 += a410 })411 expect(sum1).toBe(4)412 let sum2 = 0413 draft.get("first").a = 10414 draft.get("second").a = 20415 draft.get(key1).a = 30416 draft.get(key2).a = 40417 draft.forEach(({a}) => {418 sum2 += a419 })420 expect(sum2).toBe(100)421 })422 expect(result).not.toBe(base)423 expect(base.get("first").a).toEqual(1)424 expect(base.get("second").a).toEqual(1)425 expect(base.get(key1).a).toEqual(1)426 expect(base.get(key2).a).toEqual(1)427 expect(result.get("first").a).toEqual(10)428 expect(result.get("second").a).toEqual(20)429 expect(result.get(key1).a).toEqual(30)430 expect(result.get(key2).a).toEqual(40)431 })432433 it("supports forEach mutation", () => {434 const base = new Map([435 ["first", {id: 1, a: 1}],436 ["second", {id: 2, a: 1}]437 ])438 const result = produce(base, draft => {439 draft.forEach(item => {440 item.a = 100441 })442 })443 expect(result).not.toBe(base)444 expect(result.get("first").a).toEqual(100)445 expect(result.get("second").a).toEqual(100)446 })447448 it("can assign by key", () => {449 const nextState = produce(baseState, s => {450 // Map.prototype.set should return the Map itself451 const res = s.aMap.set("force", true)452 expect(res).toBe(s.aMap[DRAFT_STATE].draft)453 })454 expect(nextState).not.toBe(baseState)455 expect(nextState.aMap).not.toBe(baseState.aMap)456 expect(nextState.aMap.get("force")).toEqual(true)457 })458459 it("can assign by a non-primitive key", () => {460 const key = {prop: "val"}461 const value = {id: 1, a: 1}462 const base = new Map([[key, value]])463 const nextState = produce(base, s => {464 s.set(key, true)465 })466 expect(nextState).not.toBe(base)467 expect(base.get(key)).toEqual(value)468 expect(nextState.get(key)).toEqual(true)469 })470471 it("state stays the same if the the same item is assigned by key", () => {472 const nextState = produce(baseState, s => {473 s.aMap.set("jediTotal", 42)474 })475 expect(nextState).toBe(baseState)476 expect(nextState.aMap).toBe(baseState.aMap)477 })478479 it("returns 'size'", () => {480 const nextState = produce(baseState, s => {481 s.aMap.set("newKey", true)482 expect(s.aMap.size).toBe(baseState.aMap.size + 1)483 })484 expect(nextState).not.toBe(baseState)485 expect(nextState.aMap).not.toBe(baseState.aMap)486 expect(nextState.aMap.get("newKey")).toEqual(true)487 expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)488 })489490 it("can use 'delete' to remove items", () => {491 const nextState = produce(baseState, s => {492 expect(s.aMap.has("jedi")).toBe(true)basic map tests succeedingMichel Weststratebefore adoption735c402
line 493why, one step back493 expect(s.aMap.delete("jedi")).toBe(true)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 494–537why, one step back494 expect(s.aMap.has("jedi")).toBe(false)495 })496 expect(nextState.aMap).not.toBe(baseState.aMap)497 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)498 expect(baseState.aMap.has("jedi")).toBe(true)499 expect(nextState.aMap.has("jedi")).toBe(false)500 })501502 it("can use 'clear' to remove items", () => {503 const nextState = produce(baseState, s => {504 expect(s.aMap.size).not.toBe(0)505 s.aMap.clear()506 expect(s.aMap.size).toBe(0)507 })508 expect(nextState.aMap).not.toBe(baseState.aMap)509 expect(baseState.aMap.size).not.toBe(0)510 expect(nextState.aMap.size).toBe(0)511 })512513 it("support 'has'", () => {514 const nextState = produce(baseState, s => {515 expect(s.aMap.has("newKey")).toBe(false)516 s.aMap.set("newKey", true)517 expect(s.aMap.has("newKey")).toBe(true)518 })519 expect(nextState).not.toBe(baseState)520 expect(nextState.aMap).not.toBe(baseState.aMap)521 expect(baseState.aMap.has("newKey")).toBe(false)522 expect(nextState.aMap.has("newKey")).toBe(true)523 })524525 it("supports nested maps", () => {526 const base = new Map([["first", new Map([["second", {prop: "test"}]])]])527 const result = produce(base, draft => {528 draft.get("first").get("second").prop = "test1"529 })530 expect(result).not.toBe(base)531 expect(result.get("first")).not.toBe(base.get("first"))532 expect(result.get("first").get("second")).not.toBe(533 base.get("first").get("second")534 )535 expect(base.get("first").get("second").prop).toBe("test")536 expect(result.get("first").get("second").prop).toBe("test1")537 })basic map tests succeedingMichel Weststratebefore adoption735c402
lines 538–545why, one step back538539 it("treats void deletes as no-op", () => {540 const base = new Map([["x", 1]])541 const next = produce(base, d => {542 expect(d.delete("y")).toBe(false)543 })544 expect(next).toBe(base)545 })feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 546–547why, one step back546 })547fixed most testsMichel Weststratebefore adoption385c0a4
line 548why, one step back548 describe("set drafts", () => {feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 549–679why, one step back549 it("supports iteration", () => {550 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])551 const findById = (set, id) => {552 for (const item of set) {553 if (item.id === id) return item554 }555 return null556 }557 const result = produce(base, draft => {558 const obj1 = findById(draft, 1)559 const obj2 = findById(draft, 2)560 obj1.a = 2561 obj2.a = 2562 })563 expect(result).not.toBe(base)564 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))565 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))566 })567568 it("supports 'entries'", () => {569 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])570 const findById = (set, id) => {571 for (const [item1, item2] of set.entries()) {572 expect(item1).toBe(item2)573 if (item1.id === id) return item1574 }575 return null576 }577 const result = produce(base, draft => {578 const obj1 = findById(draft, 1)579 const obj2 = findById(draft, 2)580 obj1.a = 2581 obj2.a = 2582 })583 expect(result).not.toBe(base)584 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))585 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))586 })587588 it("supports 'values'", () => {589 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])590 const findById = (set, id) => {591 for (const item of set.values()) {592 if (item.id === id) return item593 }594 return null595 }596 const result = produce(base, draft => {597 const obj1 = findById(draft, 1)598 const obj2 = findById(draft, 2)599 obj1.a = 2600 obj2.a = 2601 })602 expect(result).not.toBe(base)603 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))604 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))605 })606607 it("supports 'keys'", () => {608 const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])609 const findById = (set, id) => {610 for (const item of set.keys()) {611 if (item.id === id) return item612 }613 return null614 }615 const result = produce(base, draft => {616 const obj1 = findById(draft, 1)617 const obj2 = findById(draft, 2)618 obj1.a = 2619 obj2.a = 2620 })621 expect(result).not.toBe(base)622 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))623 expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))624 })625626 it("supports forEach with mutation after reads", () => {627 const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])628 const result = produce(base, draft => {629 let sum1 = 0630 draft.forEach(({a}) => {631 sum1 += a632 })633 expect(sum1).toBe(3)634 let sum2 = 0635 draft.forEach(item => {636 item.a += 10637 sum2 += item.a638 })639 expect(sum2).toBe(23)640 })641 expect(result).not.toBe(base)642 expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 2}]))643 expect(result).toEqual(new Set([{id: 1, a: 11}, {id: 2, a: 12}]))644 })645646 it("state stays the same if the same item is added", () => {647 const nextState = produce(baseState, s => {648 s.aSet.add("Luke")649 })650 expect(nextState).toBe(baseState)651 expect(nextState.aSet).toBe(baseState.aSet)652 })653654 it("can add new items", () => {655 const nextState = produce(baseState, s => {656 // Set.prototype.set should return the Set itself657 const res = s.aSet.add("force")658 expect(res).toBe(s.aSet[DRAFT_STATE].draft)659 })660 expect(nextState).not.toBe(baseState)661 expect(nextState.aSet).not.toBe(baseState.aSet)662 expect(baseState.aSet.has("force")).toBe(false)663 expect(nextState.aSet.has("force")).toBe(true)664 })665666 it("returns 'size'", () => {667 const nextState = produce(baseState, s => {668 s.aSet.add("newKey")669 expect(s.aSet.size).toBe(baseState.aSet.size + 1)670 })671 expect(nextState).not.toBe(baseState)672 expect(nextState.aSet).not.toBe(baseState.aSet)673 expect(nextState.aSet.has("newKey")).toBe(true)674 expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)675 })676677 it("can use 'delete' to remove items", () => {678 const nextState = produce(baseState, s => {679 expect(s.aSet.has("Luke")).toBe(true)fixed most testsMichel Weststratebefore adoption385c0a4
lines 680–681why, one step back680 expect(s.aSet.delete("Luke")).toBe(true)681 expect(s.aSet.delete("Luke")).toBe(false)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 682–686why, one step back682 expect(s.aSet.has("Luke")).toBe(false)683 })684 expect(nextState.aSet).not.toBe(baseState.aSet)685 expect(baseState.aSet.has("Luke")).toBe(true)686 expect(nextState.aSet.has("Luke")).toBe(false)fixed most testsMichel Weststratebefore adoption385c0a4
line 687why, one step back687 expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 688–723why, one step back688 })689690 it("can use 'clear' to remove items", () => {691 const nextState = produce(baseState, s => {692 expect(s.aSet.size).not.toBe(0)693 s.aSet.clear()694 expect(s.aSet.size).toBe(0)695 })696 expect(nextState.aSet).not.toBe(baseState.aSet)697 expect(baseState.aSet.size).not.toBe(0)698 expect(nextState.aSet.size).toBe(0)699 })700701 it("supports 'has'", () => {702 const nextState = produce(baseState, s => {703 expect(s.aSet.has("newKey")).toBe(false)704 s.aSet.add("newKey")705 expect(s.aSet.has("newKey")).toBe(true)706 })707 expect(nextState).not.toBe(baseState)708 expect(nextState.aSet).not.toBe(baseState.aSet)709 expect(baseState.aSet.has("newKey")).toBe(false)710 expect(nextState.aSet.has("newKey")).toBe(true)711 })712713 it("supports nested sets", () => {714 const base = new Set([new Set(["Serenity"])])715 const result = produce(base, draft => {716 draft.forEach(nestedItem => nestedItem.add("Firefly"))717 })718 expect(result).not.toBe(base)719 expect(base).toEqual(new Set([new Set(["Serenity"])]))720 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))721 })722 })723style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 724–1247why, one step back724 it("supports `immerable` symbol on constructor", () => {725 class One {}726 One[immerable] = true727 const baseState = new One()728 const nextState = produce(baseState, draft => {729 expect(draft).not.toBe(baseState)730 draft.foo = true731 })732 expect(nextState).not.toBe(baseState)733 expect(nextState.foo).toBeTruthy()734 })735736 it("preserves symbol properties", () => {737 const test = Symbol("test")738 const baseState = {[test]: true}739 const nextState = produce(baseState, s => {740 expect(s[test]).toBeTruthy()741 s.foo = true742 })743 expect(nextState).toEqual({744 [test]: true,745 foo: true746 })747 })748749 it("preserves non-enumerable properties", () => {750 const baseState = {}751 // Non-enumerable object property752 Object.defineProperty(baseState, "foo", {753 value: {a: 1},754 enumerable: false755 })756 // Non-enumerable primitive property757 Object.defineProperty(baseState, "bar", {758 value: 1,759 enumerable: false760 })761 const nextState = produce(baseState, s => {762 expect(s.foo).toBeTruthy()763 expect(isEnumerable(s, "foo")).toBeFalsy()764 s.bar++765 expect(isEnumerable(s, "foo")).toBeFalsy()766 s.foo.a++767 expect(isEnumerable(s, "foo")).toBeFalsy()768 })769 expect(nextState.foo).toBeTruthy()770 expect(isEnumerable(nextState, "foo")).toBeFalsy()771 })772773 it("throws on computed properties", () => {774 const baseState = {}775 Object.defineProperty(baseState, "foo", {776 get: () => {},777 enumerable: true778 })779 expect(() => {780 produce(baseState, s => {781 // Proxies only throw once a change is made.782 if (useProxies) {783 s.modified = true784 }785 })786 }).toThrowErrorMatchingSnapshot()787 })788789 it("allows inherited computed properties", () => {790 const proto = {}791 Object.defineProperty(proto, "foo", {792 get() {793 return this.bar794 },795 set(val) {796 this.bar = val797 }798 })799 const baseState = Object.create(proto)800 produce(baseState, s => {801 expect(s.bar).toBeUndefined()802 s.foo = {}803 expect(s.bar).toBeDefined()804 expect(s.foo).toBe(s.bar)805 })806 })807808 it("supports a base state with multiple references to an object", () => {809 const obj = {}810 const res = produce({a: obj, b: obj}, d => {811 // Two drafts are created for each occurrence of an object in the base state.812 expect(d.a).not.toBe(d.b)813 d.a.z = true814 expect(d.b.z).toBeUndefined()815 })816 expect(res.b).toBe(obj)817 expect(res.a).not.toBe(res.b)818 expect(res.a.z).toBeTruthy()819 })820821 // NOTE: Except the root draft.822 it("supports multiple references to any modified draft", () => {823 const next = produce({a: {b: 1}}, d => {824 d.a.b++825 d.b = d.a826 })827 expect(next.a).toBe(next.b)828 })829830 it("can rename nested objects (no changes)", () => {831 const nextState = produce({obj: {}}, s => {832 s.foo = s.obj833 delete s.obj834 })835 expect(nextState).toEqual({foo: {}})836 })837838 // Very similar to the test before, but the reused object has one839 // property changed, one added, and one removed.840 it("can rename nested objects (with changes)", () => {841 const nextState = produce({obj: {a: 1, b: 1}}, s => {842 s.obj.a = true // change843 delete s.obj.b // delete844 s.obj.c = true // add845846 s.foo = s.obj847 delete s.obj848 })849 expect(nextState).toEqual({foo: {a: true, c: true}})850 })851852 it("can nest a draft in a new object (no changes)", () => {853 const baseState = {obj: {}}854 const nextState = produce(baseState, s => {855 s.foo = {bar: s.obj}856 delete s.obj857 })858 expect(nextState.foo.bar).toBe(baseState.obj)859 })860861 it("can nest a modified draft in a new object", () => {862 const nextState = produce({obj: {a: 1, b: 1}}, s => {863 s.obj.a = true // change864 delete s.obj.b // delete865 s.obj.c = true // add866867 s.foo = {bar: s.obj}868 delete s.obj869 })870 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})871 })872873 it("supports assigning undefined to an existing property", () => {874 const nextState = produce(baseState, s => {875 s.aProp = undefined876 })877 expect(nextState).not.toBe(baseState)878 expect(nextState.aProp).toBe(undefined)879 })880881 it("supports assigning undefined to a new property", () => {882 const baseState = {}883 const nextState = produce(baseState, s => {884 s.aProp = undefined885 })886 expect(nextState).not.toBe(baseState)887 expect(nextState.aProp).toBe(undefined)888 })889890 // NOTE: ES5 drafts only protect existing properties when revoked.891 it("revokes the draft once produce returns", () => {892 const expectRevoked = (fn, shouldThrow = true) => {893 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()894 else expect(fn).not.toThrow()895 }896897 // Test object drafts:898 let draft899 produce({a: 1, b: 1}, s => {900 draft = s901 delete s.b902 })903904 // Access known property on object draft.905 expectRevoked(() => {906 draft.a907 })908909 // Assign known property on object draft.910 expectRevoked(() => {911 draft.a = true912 })913914 // Access unknown property on object draft.915 expectRevoked(() => {916 draft.z917 }, useProxies)918919 // Assign unknown property on object draft.920 expectRevoked(() => {921 draft.z = true922 }, useProxies)923924 // Test array drafts:925 produce([1, 2], s => {926 draft = s927 s.pop()928 })929930 // Access known index of an array draft.931 expectRevoked(() => {932 draft[0]933 })934935 // Assign known index of an array draft.936 expectRevoked(() => {937 draft[0] = true938 })939940 // Access unknown index of an array draft.941 expectRevoked(() => {942 draft[1]943 }, useProxies)944945 // Assign unknown index of an array draft.946 expectRevoked(() => {947 draft[1] = true948 }, useProxies)949 })950951 it("can access a child draft that was created before the draft was modified", () => {952 produce({a: {}}, s => {953 const before = s.a954 s.b = 1955 expect(s.a).toBe(before)956 })957 })958959 it("should reflect all changes made in the draft immediately", () => {960 produce(baseState, draft => {961 draft.anArray[0] = 5962 draft.anArray.unshift("test")963 expect(enumerableOnly(draft.anArray)).toEqual(["test", 5, 2, {c: 3}, 1])964 draft.stuffz = "coffee"965 expect(draft.stuffz).toBe("coffee")966 })967 })968969 if (useProxies)970 it("throws when Object.defineProperty() is used on drafts", () => {971 expect(() => {972 produce({}, draft => {973 Object.defineProperty(draft, "xx", {974 enumerable: true,975 writeable: true,976 value: 2977 })978 })979 }).toThrowErrorMatchingSnapshot()980 })981982 it("should handle constructor correctly", () => {983 const baseState = {984 arr: new Array(),985 obj: new Object()986 }987 const result = produce(baseState, draft => {988 draft.arrConstructed = draft.arr.constructor(1)989 draft.objConstructed = draft.obj.constructor(1)990 })991 expect(result.arrConstructed).toEqual(new Array().constructor(1))992 expect(result.objConstructed).toEqual(new Object().constructor(1))993 })994995 it("should handle equality correctly - 1", () => {996 const baseState = {997 y: 3 / 0,998 z: NaN999 }1000 const nextState = produce(baseState, draft => {1001 draft.y = 4 / 01002 draft.z = NaN1003 })1004 expect(nextState).toBe(baseState)1005 })10061007 it("should handle equality correctly - 2", () => {1008 const baseState = {1009 x: -01010 }1011 const nextState = produce(baseState, draft => {1012 draft.x = +01013 })1014 expect(nextState).not.toBe(baseState)1015 expect(nextState).not.toEqual(baseState)1016 })10171018 // AKA: recursive produce calls1019 describe("nested producers", () => {1020 describe("when base state is not a draft", () => {1021 // This test ensures the global state used to manage proxies is1022 // never left in a corrupted state by a nested `produce` call.1023 it("never affects its parent producer implicitly", () => {1024 const base = {obj: {a: 1}}1025 const next = produce(base, draft => {1026 // Notice how `base.obj` is passed, not `draft.obj`1027 const obj2 = produce(base.obj, draft2 => {1028 draft2.a = 01029 })1030 expect(obj2.a).toBe(0)1031 expect(draft.obj.a).toBe(1) // effects should not be visible outside1032 })1033 expect(next).toBe(base)1034 })1035 })10361037 describe("when base state is a draft", () => {1038 it("always wraps the draft in a new draft", () => {1039 produce({}, parent => {1040 produce(parent, child => {1041 expect(child).not.toBe(parent)1042 expect(isDraft(child)).toBeTruthy()1043 expect(original(child)).toBe(parent)1044 })1045 })1046 })10471048 // Reported by: https://github.com/mweststrate/immer/issues/3431049 it("ensures each property is drafted", () => {1050 produce({a: {}, b: {}}, parent => {1051 parent.a // Access "a" but not "b"1052 produce(parent, child => {1053 child.c = 11054 expect(isDraft(child.a)).toBeTruthy()1055 expect(isDraft(child.b)).toBeTruthy()1056 })1057 })1058 })10591060 it("preserves any pending changes", () => {1061 produce({a: 1, b: 1, d: 1}, parent => {1062 parent.b = 21063 parent.c = 21064 delete parent.d1065 produce(parent, child => {1066 expect(child.a).toBe(1) // unchanged1067 expect(child.b).toBe(2) // changed1068 expect(child.c).toBe(2) // added1069 expect(child.d).toBeUndefined() // deleted1070 })1071 })1072 })1073 })10741075 describe("when base state contains a draft", () => {1076 it("wraps unowned draft with its own draft", () => {1077 produce({a: {}}, parent => {1078 produce({a: parent.a}, child => {1079 expect(child.a).not.toBe(parent.a)1080 expect(isDraft(child.a)).toBeTruthy()1081 expect(original(child.a)).toBe(parent.a)1082 })1083 })1084 })10851086 it("returns unowned draft if no changes were made", () => {1087 produce({a: {}}, parent => {1088 const result = produce({a: parent.a}, () => {})1089 expect(result.a).toBe(parent.a)1090 })1091 })10921093 it("clones the unowned draft when changes are made", () => {1094 produce({a: {}}, parent => {1095 const result = produce({a: parent.a}, child => {1096 child.a.b = 11097 })1098 expect(result.a).not.toBe(parent.a)1099 expect(result.a.b).toBe(1)1100 expect("b" in parent.a).toBeFalsy()1101 })1102 })11031104 // We cannot auto-freeze the result of a nested producer,1105 // because it may contain a draft from a parent producer.1106 it("never auto-freezes the result", () => {1107 produce({a: {}}, parent => {1108 const r = produce({a: parent.a}, child => {1109 child.b = 1 // Ensure a copy is returned.1110 })1111 expect(Object.isFrozen(r)).toBeFalsy()1112 })1113 })1114 })11151116 // "Upvalues" are variables from a parent scope.1117 it("does not finalize upvalue drafts", () => {1118 produce({a: {}, b: {}}, parent => {1119 expect(produce({}, () => parent)).toBe(parent)1120 parent.x // Ensure proxy not revoked.11211122 expect(produce({}, () => [parent])[0]).toBe(parent)1123 parent.x // Ensure proxy not revoked.11241125 expect(produce({}, () => parent.a)).toBe(parent.a)1126 parent.a.x // Ensure proxy not revoked.11271128 // Modified parent test1129 parent.c = 11130 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1131 parent.b.x // Ensure proxy not revoked.1132 })1133 })11341135 it("works with interweaved Immer instances", () => {1136 const options = {useProxies, autoFreeze}1137 const one = createPatchedImmer(options)1138 const two = createPatchedImmer(options)11391140 const base = {}1141 const result = one.produce(base, s1 =>1142 two.produce({s1}, s2 => {1143 expect(original(s2.s1)).toBe(s1)1144 s2.n = 11145 s2.s1 = one.produce({s2}, s3 => {1146 expect(original(s3.s2)).toBe(s2)1147 expect(original(s3.s2.s1)).toBe(s2.s1)1148 return s3.s2.s11149 })1150 })1151 )1152 expect(result.n).toBe(1)1153 expect(result.s1).toBe(base)1154 })1155 })11561157 if (useProxies)1158 it("throws when Object.setPrototypeOf() is used on a draft", () => {1159 produce({}, draft => {1160 expect(() =>1161 Object.setPrototypeOf(draft, Array)1162 ).toThrowErrorMatchingSnapshot()1163 })1164 })11651166 it("supports the 'in' operator", () => {1167 produce(baseState, draft => {1168 // Known property1169 expect("anArray" in draft).toBe(true)1170 expect(Reflect.has(draft, "anArray")).toBe(true)11711172 // Unknown property1173 expect("bla" in draft).toBe(false)1174 expect(Reflect.has(draft, "bla")).toBe(false)11751176 // Known index1177 expect(0 in draft.anArray).toBe(true)1178 expect("0" in draft.anArray).toBe(true)1179 expect(Reflect.has(draft.anArray, 0)).toBe(true)1180 expect(Reflect.has(draft.anArray, "0")).toBe(true)11811182 // Unknown index1183 expect(17 in draft.anArray).toBe(false)1184 expect("17" in draft.anArray).toBe(false)1185 expect(Reflect.has(draft.anArray, 17)).toBe(false)1186 expect(Reflect.has(draft.anArray, "17")).toBe(false)1187 })1188 })11891190 it("'this' should not be bound anymore - 1", () => {1191 const base = {x: 3}1192 const next1 = produce(base, function() {1193 expect(this).toBe(undefined)1194 })1195 })11961197 it("'this' should not be bound anymore - 2", () => {1198 const incrementor = produce(function() {1199 expect(this).toBe(undefined)1200 })1201 incrementor()1202 })12031204 it("should be possible to use dynamic bound this", () => {1205 const world = {1206 counter: {count: 1},1207 inc: produce(function(draft) {1208 expect(this).toBe(world)1209 draft.counter.count = this.counter.count + 11210 })1211 }12121213 expect(world.inc(world).counter.count).toBe(2)1214 })12151216 // See here: https://github.com/mweststrate/immer/issues/891217 it("supports the spread operator", () => {1218 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1219 const result = produce(base, draft => {1220 draft.foo = {x: 1, ...draft.foo, y: 1}1221 draft.bar = [1, ...draft.bar, 1]1222 })1223 expect(result).toEqual({1224 foo: {x: 0, y: 1},1225 bar: [1, 0, 0, 1]1226 })1227 })12281229 it("processes with lodash.set", () => {1230 const base = [{id: 1, a: 1}]1231 const result = produce(base, draft => {1232 lodash.set(draft, "[0].a", 2)1233 })1234 expect(base[0].a).toEqual(1)1235 expect(result[0].a).toEqual(2)1236 })12371238 it("processes with lodash.find", () => {1239 const base = [{id: 1, a: 1}]1240 const result = produce(base, draft => {1241 const obj1 = lodash.find(draft, {id: 1})1242 lodash.set(obj1, "a", 2)1243 })1244 expect(base[0].a).toEqual(1)1245 expect(result[0].a).toEqual(2)1246 })1247test: tried to reproduce #469Michel Weststratebefore adoptione504e0b
lines 1248–1266why, one step back1248 autoFreeze &&1249 test("issue #469, state not frozen", () => {1250 const project = produce(1251 {1252 id: 1,1253 tracks: [{id: 1}]1254 },1255 () => {}1256 )12571258 expect(() => {1259 project.id = 2 // Does not throw error1260 }).toThrowError("Cannot assign to read only property 'id'")12611262 expect(() => {1263 Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1264 }).toThrowError("Cannot assign to read only property 'id'")1265 })1266style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1267–1538why, one step back1267 describe("recipe functions", () => {1268 it("can return a new object", () => {1269 const base = {x: 3}1270 const res = produce(base, d => {1271 return {x: d.x + 1}1272 })1273 expect(res).not.toBe(base)1274 expect(res).toEqual({x: 4})1275 })12761277 it("can return the draft", () => {1278 const base = {x: 3}1279 const res = produce(base, d => {1280 d.x = 41281 return d1282 })1283 expect(res).not.toBe(base)1284 expect(res).toEqual({x: 4})1285 })12861287 it("can return an unmodified child draft", () => {1288 const base = {a: {}}1289 const res = produce(base, d => {1290 return d.a1291 })1292 expect(res).toBe(base.a)1293 })12941295 // TODO: Avoid throwing if only the child draft was modified.1296 it("cannot return a modified child draft", () => {1297 const base = {a: {}}1298 expect(() => {1299 produce(base, d => {1300 d.a.b = 11301 return d.a1302 })1303 }).toThrowErrorMatchingSnapshot()1304 })13051306 it("can return a frozen object", () => {1307 const res = deepFreeze([{x: 3}])1308 expect(produce({}, () => res)).toBe(res)1309 })13101311 it("can return an object with two references to another object", () => {1312 const next = produce({}, d => {1313 const obj = {}1314 return {obj, arr: [obj]}1315 })1316 expect(next.obj).toBe(next.arr[0])1317 })13181319 it("can return an object with two references to an unmodified draft", () => {1320 const base = {a: {}}1321 const next = produce(base, d => {1322 return [d.a, d.a]1323 })1324 expect(next[0]).toBe(base.a)1325 expect(next[0]).toBe(next[1])1326 })13271328 it("cannot return an object that references itself", () => {1329 const res = {}1330 res.self = res1331 expect(() => {1332 produce(res, () => res.self)1333 }).toThrowErrorMatchingSnapshot()1334 })1335 })13361337 describe("async recipe function", () => {1338 it("can modify the draft", () => {1339 const base = {a: 0, b: 0}1340 return produce(base, async d => {1341 d.a = 11342 await Promise.resolve()1343 d.b = 11344 }).then(res => {1345 expect(res).not.toBe(base)1346 expect(res).toEqual({a: 1, b: 1})1347 })1348 })13491350 it("works with rejected promises", () => {1351 let draft1352 const base = {a: 0, b: 0}1353 const err = new Error("passed")1354 return produce(base, d => {1355 draft = d1356 draft.b = 11357 return Promise.reject(err)1358 }).then(1359 () => {1360 throw "failed"1361 },1362 e => {1363 expect(e).toBe(err)1364 expect(() => draft.a).toThrowErrorMatchingSnapshot()1365 }1366 )1367 })13681369 it("supports recursive produce calls after await", () => {1370 const base = {obj: {k: 1}}1371 return produce(base, d => {1372 const obj = d.obj1373 delete d.obj1374 return Promise.resolve().then(() => {1375 d.a = produce({}, d => {1376 d.b = obj // Assign a draft owned by the parent scope.1377 })13781379 // Auto-freezing is prevented when an unowned draft exists.1380 expect(Object.isFrozen(d.a)).toBeFalsy()13811382 // Ensure `obj` is not revoked.1383 obj.c = 11384 })1385 }).then(res => {1386 expect(res).not.toBe(base)1387 expect(res).toEqual({1388 a: {b: {k: 1, c: 1}}1389 })1390 })1391 })1392 })13931394 it("throws when the draft is modified and another object is returned", () => {1395 const base = {x: 3}1396 expect(() => {1397 produce(base, draft => {1398 draft.x = 41399 return {x: 5}1400 })1401 }).toThrowErrorMatchingSnapshot()1402 })14031404 it("should fix #117 - 1", () => {1405 const reducer = (state, action) =>1406 produce(state, draft => {1407 switch (action.type) {1408 case "SET_STARTING_DOTS":1409 return draft.availableStartingDots.map(a => a)1410 default:1411 break1412 }1413 })1414 const base = {1415 availableStartingDots: [1416 {dots: 4, count: 1},1417 {dots: 3, count: 2},1418 {dots: 2, count: 3},1419 {dots: 1, count: 4}1420 ]1421 }1422 const next = reducer(base, {type: "SET_STARTING_DOTS"})1423 expect(next).toEqual(base.availableStartingDots)1424 expect(next).not.toBe(base.availableStartingDots)1425 })14261427 it("should fix #117 - 2", () => {1428 const reducer = (state, action) =>1429 produce(state, draft => {1430 switch (action.type) {1431 case "SET_STARTING_DOTS":1432 return {1433 dots: draft.availableStartingDots.map(a => a)1434 }1435 default:1436 break1437 }1438 })1439 const base = {1440 availableStartingDots: [1441 {dots: 4, count: 1},1442 {dots: 3, count: 2},1443 {dots: 2, count: 3},1444 {dots: 1, count: 4}1445 ]1446 }1447 const next = reducer(base, {type: "SET_STARTING_DOTS"})1448 expect(next).toEqual({dots: base.availableStartingDots})1449 })14501451 it("cannot always detect noop assignments - 0", () => {1452 const baseState = {x: {y: 3}}1453 const nextState = produce(baseState, d => {1454 const a = d.x1455 d.x = a1456 })1457 expect(nextState).toBe(baseState)1458 })14591460 it("cannot always detect noop assignments - 1", () => {1461 const baseState = {x: {y: 3}}1462 const nextState = produce(baseState, d => {1463 const a = d.x1464 d.x = 41465 d.x = a1466 })1467 // Ideally, this should actually be the same instances1468 // but this would be pretty expensive to detect,1469 // so we don't atm1470 expect(nextState).not.toBe(baseState)1471 })14721473 it("cannot always detect noop assignments - 2", () => {1474 const baseState = {x: {y: 3}}1475 const nextState = produce(baseState, d => {1476 const a = d.x1477 const stuff = a.y + 31478 d.x = 41479 d.x = a1480 })1481 // Ideally, this should actually be the same instances1482 // but this would be pretty expensive to detect,1483 // so we don't atm1484 expect(nextState).not.toBe(baseState)1485 })14861487 it("cannot always detect noop assignments - 3", () => {1488 const baseState = {x: 3}1489 const nextState = produce(baseState, d => {1490 d.x = 31491 })1492 expect(nextState).toBe(baseState)1493 })14941495 it("cannot always detect noop assignments - 4", () => {1496 const baseState = {x: 3}1497 const nextState = produce(baseState, d => {1498 d.x = 41499 d.x = 31500 })1501 // Ideally, this should actually be the same instances1502 // but this would be pretty expensive to detect,1503 // so we don't atm1504 expect(nextState).not.toBe(baseState)1505 })15061507 it("cannot produce undefined by returning undefined", () => {1508 const base = 31509 expect(produce(base, () => 4)).toBe(4)1510 expect(produce(base, () => null)).toBe(null)1511 expect(produce(base, () => undefined)).toBe(3)1512 expect(produce(base, () => {})).toBe(3)1513 expect(produce(base, () => nothing)).toBe(undefined)15141515 expect(produce({}, () => undefined)).toEqual({})1516 expect(produce({}, () => nothing)).toBe(undefined)1517 expect(produce(3, () => nothing)).toBe(undefined)15181519 expect(produce(() => undefined)({})).toEqual({})1520 expect(produce(() => nothing)({})).toBe(undefined)1521 expect(produce(() => nothing)(3)).toBe(undefined)1522 })15231524 describe("base state type", () => {1525 testObjectTypes(produce)1526 testLiteralTypes(produce)1527 })15281529 afterEach(() => {1530 expect(baseState).toBe(origBaseState)1531 expect(baseState).toEqual(createBaseState())1532 })15331534 class Foo {}1535 function createBaseState() {1536 const data = {1537 anInstance: new Foo(),1538 anArray: [3, 2, {c: 3}, 1],feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1539–1550why, one step back1539 aMap: new Map([1540 ["jedi", {name: "Luke", skill: 10}],1541 ["jediTotal", 42],1542 ["force", "these aren't the droids you're looking for"]1543 ]),1544 aSet: new Set([1545 "Luke",1546 42,1547 {1548 jedi: "Yoda"1549 }1550 ]),style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1551–1600why, one step back1551 aProp: "hi",1552 anObject: {1553 nested: {1554 yummie: true1555 },1556 coffee: false1557 }1558 }1559 return autoFreeze ? deepFreeze(data) : data1560 }1561 })15621563 describe(`isDraft - ${name}`, () => {1564 it("returns true for object drafts", () => {1565 produce({}, state => {1566 expect(isDraft(state)).toBeTruthy()1567 })1568 })1569 it("returns true for array drafts", () => {1570 produce([], state => {1571 expect(isDraft(state)).toBeTruthy()1572 })1573 })1574 it("returns true for objects nested in object drafts", () => {1575 produce({a: {b: {}}}, state => {1576 expect(isDraft(state.a)).toBeTruthy()1577 expect(isDraft(state.a.b)).toBeTruthy()1578 })1579 })1580 it("returns false for new objects added to a draft", () => {1581 produce({}, state => {1582 state.a = {}1583 expect(isDraft(state.a)).toBeFalsy()1584 })1585 })1586 it("returns false for objects returned by the producer", () => {1587 const object = produce(null, Object.create)1588 expect(isDraft(object)).toBeFalsy()1589 })1590 it("returns false for arrays returned by the producer", () => {1591 const array = produce(null, _ => [])1592 expect(isDraft(array)).toBeFalsy()1593 })1594 it("returns false for object drafts returned by the producer", () => {1595 const object = produce({}, state => state)1596 expect(isDraft(object)).toBeFalsy()1597 })1598 it("returns false for array drafts returned by the producer", () => {1599 const array = produce([], state => state)1600 expect(isDraft(array)).toBeFalsy()feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1601–1603why, one step back1601 })1602 })1603fixed most testsMichel Weststratebefore adoption385c0a4
line 1604why, one step back1604 describe(`complex nesting map / set / object`, () => {feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 1605–1659why, one step back1605 const a = {a: 1}1606 const b = {b: 2}1607 const c = {c: 3}1608 const set1 = new Set([a, b])1609 const set2 = new Set([c])1610 const map = new Map([["set1", set1], ["set2", set2]])1611 const base = {map}16121613 function first(set) {1614 return Array.from(set.values())[0]1615 }16161617 function second(set) {1618 return Array.from(set.values())[1]1619 }16201621 test(`modify deep object`, () => {1622 const [res, patches] = produceWithPatches(base, draft => {1623 const v = first(draft.map.get("set1"))1624 expect(original(v)).toBe(a)1625 expect(v).toEqual(a)1626 expect(v).not.toBe(a)1627 v.a++1628 })1629 expect(res).toMatchSnapshot()1630 expect(patches).toMatchSnapshot()1631 expect(a.a).toBe(1)1632 expect(base.map.get("set1")).toBe(set1)1633 expect(first(base.map.get("set1"))).toBe(a)1634 expect(res).not.toBe(base)1635 expect(res.map).not.toBe(base.map)1636 expect(res.map.get("set1")).not.toBe(base.map.get("set1"))1637 expect(second(base.map.get("set1"))).toBe(b)1638 expect(base.map.get("set2")).toBe(set2)1639 expect(first(res.map.get("set1"))).toEqual({a: 2})1640 })16411642 test(`modify deep object - keep value`, () => {1643 const [res, patches] = produceWithPatches(base, draft => {1644 const v = first(draft.map.get("set1"))1645 expect(original(v)).toBe(a)1646 expect(v).toEqual(a)1647 expect(v).not.toBe(a)1648 v.a = 1 // same value1649 })1650 expect(a.a).toBe(1)1651 expect(base.map.get("set1")).toBe(set1)1652 expect(first(base.map.get("set1"))).toBe(a)1653 expect(res).toBe(base)1654 expect(res.map).toBe(base.map)1655 expect(res.map.get("set1")).toBe(base.map.get("set1"))1656 expect(first(res.map.get("set1"))).toBe(a)1657 expect(second(base.map.get("set1"))).toBe(b)1658 expect(base.map.get("set2")).toBe(set2)1659 expect(patches.length).toBe(0)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1660–1663why, one step back1660 })1661 })1662}1663chore: improve more testsaleclarsonbefore adoption4f59b12
line 1664why, one step back1664function testObjectTypes(produce) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1665–1717why, one step back1665 class Foo {1666 constructor(foo) {1667 this.foo = foo1668 this[immerable] = true1669 }1670 }1671 const values = {1672 "empty object": {},1673 "plain object": {a: 1, b: 2},1674 "object (no prototype)": Object.create(null),1675 "empty array": [],1676 "plain array": [1, 2],1677 "class instance (draftable)": new Foo(1)1678 }1679 for (const name in values) {1680 const value = values[name]1681 const copy = shallowCopy(value)1682 testObjectType(name, value)1683 testObjectType(name + " (frozen)", Object.freeze(copy))1684 }1685 function testObjectType(name, base) {1686 describe(name, () => {1687 it("creates a draft", () => {1688 produce(base, draft => {1689 expect(draft).not.toBe(base)1690 expect(shallowCopy(draft, true)).toEqual(base)1691 })1692 })16931694 it("preserves the prototype", () => {1695 const proto = Object.getPrototypeOf(base)1696 produce(base, draft => {1697 expect(Object.getPrototypeOf(draft)).toBe(proto)1698 })1699 })17001701 it("returns the base state when no changes are made", () => {1702 expect(produce(base, () => {})).toBe(base)1703 })17041705 it("returns a copy when changes are made", () => {1706 const random = Math.random()1707 const result = produce(base, draft => {1708 draft[0] = random1709 })1710 expect(result).not.toBe(base)1711 expect(result.constructor).toBe(base.constructor)1712 expect(result[0]).toBe(random)1713 })1714 })1715 }1716}1717chore: improve more testsaleclarsonbefore adoption4f59b12
line 1718why, one step back1718function testLiteralTypes(produce) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1719–1771why, one step back1719 class Foo {}1720 const values = {1721 "falsy number": 0,1722 "truthy number": 1,1723 "negative number": -1,1724 NaN: NaN,1725 infinity: 1 / 0,1726 true: true,1727 false: false,1728 "empty string": "",1729 "truthy string": "1",1730 null: null,1731 undefined: undefined,17321733 /**1734 * These objects are treated as literals because Immer1735 * does not know how to draft them.1736 */1737 function: () => {},1738 "regexp object": /.+/g,1739 "boxed number": new Number(0),1740 "boxed string": new String(""),1741 "boxed boolean": new Boolean(),1742 "date object": new Date(),1743 "class instance (not draftable)": new Foo()1744 }1745 for (const name in values) {1746 describe(name, () => {1747 const value = values[name]17481749 it("does not create a draft", () => {1750 produce(value, draft => {1751 expect(draft).toBe(value)1752 })1753 })17541755 it("returns the base state when no changes are made", () => {1756 expect(produce(value, () => {})).toBe(value)1757 })17581759 if (value && typeof value == "object") {1760 it("does not return a copy when changes are made", () => {1761 expect(1762 produce(value, draft => {1763 draft.foo = true1764 })1765 ).toBe(value)1766 })1767 }1768 })1769 }1770}1771feat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
line 1772why, one step back1772function enumerableOnly(x) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 1773–1779why, one step back1773 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1774 each(copy, (prop, value) => {1775 if (value && typeof value === "object") {1776 copy[prop] = enumerableOnly(value)1777 }1778 })1779 return copyfeat: drop typescript@3.0 supportaleclarsonbefore adoption66e51e1
line 1780why, one step back1780}