base.js
This file
Path
__tests__/base.js
1,274 lines · 44.8 KiB · JavaScript
Last changed by
refactor(ts): simplify IProduce type testsAlec Larsonbefore adoptionbce282d
History of this fileTake it
1"use strict"2import {Immer, nothing, original, isDraft, immerable} from "../src/index"3import {each, shallowCopy, isEnumerable} from "../src/common"4import deepFreeze from "deep-freeze"5import cloneDeep from "lodash.clonedeep"6import * as lodash from "lodash"78jest.setTimeout(1000)910test("immer should have no dependencies", () => {11 expect(require("../package.json").dependencies).toBeUndefined()12})1314runBaseTest("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)2021function runBaseTest(name, useProxies, autoFreeze, useListener) {22 const listener = useListener ? function() {} : undefined23 const {produce} = createPatchedImmer({24 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} = immer34 immer.produce = (...args) =>35 typeof args[1] === "function" && args.length < 336 ? produce(...args, listener)37 : produce(...args)3839 return immer40 }4142 describe(`base functionality - ${name}`, () => {43 let baseState44 let origBaseState4546 beforeEach(() => {47 origBaseState = baseState = createBaseState()48 })4950 it("returns the original state when no changes are made", () => {51 const nextState = produce(baseState, s => {52 expect(s.aProp).toBe("hi")53 expect(s.anObject.nested).toMatchObject({yummie: true})54 })55 expect(nextState).toBe(baseState)56 })5758 it("does structural sharing", () => {59 const random = Math.random()60 const nextState = produce(baseState, s => {61 s.aProp = random62 })63 expect(nextState).not.toBe(baseState)64 expect(nextState.aProp).toBe(random)65 expect(nextState.nested).toBe(baseState.nested)66 })6768 it("deep change bubbles up", () => {69 const nextState = produce(baseState, s => {70 s.anObject.nested.yummie = false71 })72 expect(nextState).not.toBe(baseState)73 expect(nextState.anObject).not.toBe(baseState.anObject)74 expect(baseState.anObject.nested.yummie).toBe(true)75 expect(nextState.anObject.nested.yummie).toBe(false)76 expect(nextState.anArray).toBe(baseState.anArray)77 })7879 it("can add props", () => {80 const nextState = produce(baseState, s => {81 s.anObject.cookie = {tasty: true}82 })83 expect(nextState).not.toBe(baseState)84 expect(nextState.anObject).not.toBe(baseState.anObject)85 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)86 expect(nextState.anObject.cookie).toEqual({tasty: true})87 })8889 it("can delete props", () => {90 const nextState = produce(baseState, s => {91 delete s.anObject.nested92 })93 expect(nextState).not.toBe(baseState)94 expect(nextState.anObject).not.toBe(baseState.anObject)95 expect(nextState.anObject.nested).toBe(undefined)96 })9798 // Found by: https://github.com/mweststrate/immer/pull/26799 it("can delete props added in the producer", () => {100 const nextState = produce(baseState, s => {101 s.anObject.test = true102 delete s.anObject.test103 })104 if (useProxies) {105 expect(nextState).not.toBe(baseState)106 expect(nextState).toEqual(baseState)107 } else {108 // The copy is avoided in ES5.109 expect(nextState).toBe(baseState)110 }111 })112113 // Found by: https://github.com/mweststrate/immer/issues/328114 it("can set a property that was just deleted", () => {115 const baseState = {a: 1}116 const nextState = produce(baseState, s => {117 delete s.a118 s.a = 2119 })120 expect(nextState.a).toBe(2)121 })122123 it("can set a property to its original value after deleting it", () => {124 const baseState = {a: {b: 1}}125 const nextState = produce(baseState, s => {126 const a = s.a127 delete s.a128 s.a = a129 })130 if (useProxies) {131 expect(nextState).not.toBe(baseState)132 expect(nextState).toEqual(baseState)133 } else {134 // The copy is avoided in ES5.135 expect(nextState).toBe(baseState)136 }137 })138139 it("can get property descriptors", () => {140 const getDescriptor = Object.getOwnPropertyDescriptor141 const baseState = deepFreeze([{a: 1}])142 produce(baseState, arr => {143 const obj = arr[0]144 const desc = {145 configurable: true,146 enumerable: true,147 ...(useProxies && {writable: true})148 }149150 // Known property151 expect(getDescriptor(obj, "a")).toMatchObject(desc)152 expect(getDescriptor(arr, 0)).toMatchObject(desc)153154 // Deleted property155 delete obj.a156 arr.pop()157 expect(getDescriptor(obj, "a")).toBeUndefined()158 expect(getDescriptor(arr, 0)).toBeUndefined()159160 // Unknown property161 expect(getDescriptor(obj, "b")).toBeUndefined()162 expect(getDescriptor(arr, 100)).toBeUndefined()163164 // Added property165 obj.b = 2166 arr[100] = 1167 expect(getDescriptor(obj, "b")).toBeDefined()168 expect(getDescriptor(arr, 100)).toBeDefined()169 })170 })171172 describe("array drafts", () => {173 it("supports Array.isArray()", () => {174 const nextState = produce(baseState, s => {175 expect(Array.isArray(s.anArray)).toBeTruthy()176 s.anArray.push(1)177 })178 expect(Array.isArray(nextState.anArray)).toBeTruthy()179 })180181 it("supports index access", () => {182 const value = baseState.anArray[0]183 const nextState = produce(baseState, s => {184 expect(s.anArray[0]).toBe(value)185 })186 expect(nextState).toBe(baseState)187 })188189 it("supports iteration", () => {190 const base = [{id: 1, a: 1}, {id: 2, a: 1}]191 const findById = (collection, id) => {192 for (const item of collection) {193 if (item.id === id) return item194 }195 return null196 }197 const result = produce(base, draft => {198 const obj1 = findById(draft, 1)199 const obj2 = findById(draft, 2)200 obj1.a = 2201 obj2.a = 2202 })203 expect(result[0].a).toEqual(2)204 expect(result[1].a).toEqual(2)205 })206207 it("can assign an index via bracket notation", () => {208 const nextState = produce(baseState, s => {209 s.anArray[3] = true210 })211 expect(nextState).not.toBe(baseState)212 expect(nextState.anArray).not.toBe(baseState.anArray)213 expect(nextState.anArray[3]).toEqual(true)214 })215216 it("can use splice() to both add and remove items", () => {217 const nextState = produce(baseState, s => {218 s.anArray.splice(1, 1, "a", "b")219 })220 expect(nextState.anArray).not.toBe(baseState.anArray)221 expect(nextState.anArray[1]).toBe("a")222 expect(nextState.anArray[2]).toBe("b")223 })224225 it("can truncate via the length property", () => {226 const baseLength = baseState.anArray.length227 const nextState = produce(baseState, s => {228 s.anArray.length = baseLength - 1229 })230 expect(nextState.anArray).not.toBe(baseState.anArray)231 expect(nextState.anArray.length).toBe(baseLength - 1)232 })233234 it("can extend via the length property", () => {235 const baseLength = baseState.anArray.length236 const nextState = produce(baseState, s => {237 s.anArray.length = baseLength + 1238 })239 expect(nextState.anArray).not.toBe(baseState.anArray)240 expect(nextState.anArray.length).toBe(baseLength + 1)241 })242243 // Reported here: https://github.com/mweststrate/immer/issues/116244 it("can pop then push", () => {245 const nextState = produce([1, 2, 3], s => {246 s.pop()247 s.push(100)248 })249 expect(nextState).toEqual([1, 2, 100])250 })251252 it("can be sorted", () => {253 const baseState = [3, 1, 2]254 const nextState = produce(baseState, s => {255 s.sort()256 })257 expect(nextState).not.toBe(baseState)258 expect(nextState).toEqual([1, 2, 3])259 })260261 it("supports modifying nested objects", () => {262 const baseState = [{a: 1}, {}]263 const nextState = produce(baseState, s => {264 s[0].a++265 s[1].a = 0266 })267 expect(nextState).not.toBe(baseState)268 expect(nextState[0].a).toBe(2)269 expect(nextState[1].a).toBe(0)270 })271272 it("never preserves non-numeric properties", () => {273 const baseState = []274 baseState.x = 7275 const nextState = produce(baseState, s => {276 s.push(3)277 })278 expect("x" in nextState).toBeFalsy()279 })280281 if (useProxies) {282 it("throws when a non-numeric property is added", () => {283 expect(() => {284 produce([], d => {285 d.x = 3286 })287 }).toThrowErrorMatchingSnapshot()288 })289290 it("throws when a non-numeric property is deleted", () => {291 expect(() => {292 const baseState = []293 baseState.x = 7294 produce(baseState, d => {295 delete d.x296 })297 }).toThrowErrorMatchingSnapshot()298 })299 }300 })301302 it("supports `immerable` symbol on constructor", () => {303 class One {}304 One[immerable] = true305 const baseState = new One()306 const nextState = produce(baseState, draft => {307 expect(draft).not.toBe(baseState)308 draft.foo = true309 })310 expect(nextState).not.toBe(baseState)311 expect(nextState.foo).toBeTruthy()312 })313314 it("preserves symbol properties", () => {315 const test = Symbol("test")316 const baseState = {[test]: true}317 const nextState = produce(baseState, s => {318 expect(s[test]).toBeTruthy()319 s.foo = true320 })321 expect(nextState).toEqual({322 [test]: true,323 foo: true324 })325 })326327 it("preserves non-enumerable properties", () => {328 const baseState = {}329 // Non-enumerable object property330 Object.defineProperty(baseState, "foo", {331 value: {a: 1},332 enumerable: false333 })334 // Non-enumerable primitive property335 Object.defineProperty(baseState, "bar", {336 value: 1,337 enumerable: false338 })339 const nextState = produce(baseState, s => {340 expect(s.foo).toBeTruthy()341 expect(isEnumerable(s, "foo")).toBeFalsy()342 s.bar++343 expect(isEnumerable(s, "foo")).toBeFalsy()344 s.foo.a++345 expect(isEnumerable(s, "foo")).toBeFalsy()346 })347 expect(nextState.foo).toBeTruthy()348 expect(isEnumerable(nextState, "foo")).toBeFalsy()349 })350351 it("throws on computed properties", () => {352 const baseState = {}353 Object.defineProperty(baseState, "foo", {354 get: () => {},355 enumerable: true356 })357 expect(() => {358 produce(baseState, s => {359 // Proxies only throw once a change is made.360 if (useProxies) {361 s.modified = true362 }363 })364 }).toThrowErrorMatchingSnapshot()365 })366367 it("allows inherited computed properties", () => {368 const proto = {}369 Object.defineProperty(proto, "foo", {370 get() {371 return this.bar372 },373 set(val) {374 this.bar = val375 }376 })377 const baseState = Object.create(proto)378 produce(baseState, s => {379 expect(s.bar).toBeUndefined()380 s.foo = {}381 expect(s.bar).toBeDefined()382 expect(s.foo).toBe(s.bar)383 })384 })385386 it("supports a base state with multiple references to an object", () => {387 const obj = {}388 const res = produce({a: obj, b: obj}, d => {389 // Two drafts are created for each occurrence of an object in the base state.390 expect(d.a).not.toBe(d.b)391 d.a.z = true392 expect(d.b.z).toBeUndefined()393 })394 expect(res.b).toBe(obj)395 expect(res.a).not.toBe(res.b)396 expect(res.a.z).toBeTruthy()397 })398399 // NOTE: Except the root draft.400 it("supports multiple references to any modified draft", () => {401 const next = produce({a: {b: 1}}, d => {402 d.a.b++403 d.b = d.a404 })405 expect(next.a).toBe(next.b)406 })407408 it("can rename nested objects (no changes)", () => {409 const nextState = produce({obj: {}}, s => {410 s.foo = s.obj411 delete s.obj412 })413 expect(nextState).toEqual({foo: {}})414 })415416 // Very similar to the test before, but the reused object has one417 // property changed, one added, and one removed.418 it("can rename nested objects (with changes)", () => {419 const nextState = produce({obj: {a: 1, b: 1}}, s => {420 s.obj.a = true // change421 delete s.obj.b // delete422 s.obj.c = true // add423424 s.foo = s.obj425 delete s.obj426 })427 expect(nextState).toEqual({foo: {a: true, c: true}})428 })429430 it("can nest a draft in a new object (no changes)", () => {431 const baseState = {obj: {}}432 const nextState = produce(baseState, s => {433 s.foo = {bar: s.obj}434 delete s.obj435 })436 expect(nextState.foo.bar).toBe(baseState.obj)437 })438439 it("can nest a modified draft in a new object", () => {440 const nextState = produce({obj: {a: 1, b: 1}}, s => {441 s.obj.a = true // change442 delete s.obj.b // delete443 s.obj.c = true // add444445 s.foo = {bar: s.obj}446 delete s.obj447 })448 expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})449 })450451 it("supports assigning undefined to an existing property", () => {452 const nextState = produce(baseState, s => {453 s.aProp = undefined454 })455 expect(nextState).not.toBe(baseState)456 expect(nextState.aProp).toBe(undefined)457 })458459 it("supports assigning undefined to a new property", () => {460 const baseState = {}461 const nextState = produce(baseState, s => {462 s.aProp = undefined463 })464 expect(nextState).not.toBe(baseState)465 expect(nextState.aProp).toBe(undefined)466 })467468 // NOTE: ES5 drafts only protect existing properties when revoked.469 it("revokes the draft once produce returns", () => {470 const expectRevoked = (fn, shouldThrow = true) => {471 if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()472 else expect(fn).not.toThrow()473 }474475 // Test object drafts:476 let draft477 produce({a: 1, b: 1}, s => {478 draft = s479 delete s.b480 })481482 // Access known property on object draft.483 expectRevoked(() => {484 draft.a485 })486487 // Assign known property on object draft.488 expectRevoked(() => {489 draft.a = true490 })491492 // Access unknown property on object draft.493 expectRevoked(() => {494 draft.z495 }, useProxies)496497 // Assign unknown property on object draft.498 expectRevoked(() => {499 draft.z = true500 }, useProxies)501502 // Test array drafts:503 produce([1, 2], s => {504 draft = s505 s.pop()506 })507508 // Access known index of an array draft.509 expectRevoked(() => {510 draft[0]511 })512513 // Assign known index of an array draft.514 expectRevoked(() => {515 draft[0] = true516 })517518 // Access unknown index of an array draft.519 expectRevoked(() => {520 draft[1]521 }, useProxies)522523 // Assign unknown index of an array draft.524 expectRevoked(() => {525 draft[1] = true526 }, useProxies)527 })528529 it("can access a child draft that was created before the draft was modified", () => {530 produce({a: {}}, s => {531 const before = s.a532 s.b = 1533 expect(s.a).toBe(before)534 })535 })536537 it("should reflect all changes made in the draft immediately", () => {538 produce(baseState, draft => {539 draft.anArray[0] = 5540 draft.anArray.unshift("test")541 expect(enumerableOnly(draft.anArray)).toEqual([542 "test",543 5,544 2,545 {c: 3},546 1547 ])548 draft.stuffz = "coffee"549 expect(draft.stuffz).toBe("coffee")550 })551 })552553 if (useProxies)554 it("throws when Object.defineProperty() is used on drafts", () => {555 expect(() => {556 produce({}, draft => {557 Object.defineProperty(draft, "xx", {558 enumerable: true,559 writeable: true,560 value: 2561 })562 })563 }).toThrowErrorMatchingSnapshot()564 })565566 it("should handle constructor correctly", () => {567 const baseState = {568 arr: new Array(),569 obj: new Object()570 }571 const result = produce(baseState, draft => {572 draft.arrConstructed = draft.arr.constructor(1)573 draft.objConstructed = draft.obj.constructor(1)574 })575 expect(result.arrConstructed).toEqual(new Array().constructor(1))576 expect(result.objConstructed).toEqual(new Object().constructor(1))577 })578579 it("should handle equality correctly - 1", () => {580 const baseState = {581 y: 3 / 0,582 z: NaN583 }584 const nextState = produce(baseState, draft => {585 draft.y = 4 / 0586 draft.z = NaN587 })588 expect(nextState).toBe(baseState)589 })590591 it("should handle equality correctly - 2", () => {592 const baseState = {593 x: -0594 }595 const nextState = produce(baseState, draft => {596 draft.x = +0597 })598 expect(nextState).not.toBe(baseState)599 expect(nextState).not.toEqual(baseState)600 })601602 // AKA: recursive produce calls603 describe("nested producers", () => {604 describe("when base state is not a draft", () => {605 // This test ensures the global state used to manage proxies is606 // never left in a corrupted state by a nested `produce` call.607 it("never affects its parent producer implicitly", () => {608 const base = {obj: {a: 1}}609 const next = produce(base, draft => {610 // Notice how `base.obj` is passed, not `draft.obj`611 const obj2 = produce(base.obj, draft2 => {612 draft2.a = 0613 })614 expect(obj2.a).toBe(0)615 expect(draft.obj.a).toBe(1) // effects should not be visible outside616 })617 expect(next).toBe(base)618 })619 })620621 describe("when base state is a draft", () => {622 it("always wraps the draft in a new draft", () => {623 produce({}, parent => {624 produce(parent, child => {625 expect(child).not.toBe(parent)626 expect(isDraft(child)).toBeTruthy()627 expect(original(child)).toBe(parent)628 })629 })630 })631632 // Reported by: https://github.com/mweststrate/immer/issues/343633 it("ensures each property is drafted", () => {634 produce({a: {}, b: {}}, parent => {635 parent.a // Access "a" but not "b"636 produce(parent, child => {637 child.c = 1638 expect(isDraft(child.a)).toBeTruthy()639 expect(isDraft(child.b)).toBeTruthy()640 })641 })642 })643644 it("preserves any pending changes", () => {645 produce({a: 1, b: 1, d: 1}, parent => {646 parent.b = 2647 parent.c = 2648 delete parent.d649 produce(parent, child => {650 expect(child.a).toBe(1) // unchanged651 expect(child.b).toBe(2) // changed652 expect(child.c).toBe(2) // added653 expect(child.d).toBeUndefined() // deleted654 })655 })656 })657 })658659 describe("when base state contains a draft", () => {660 it("wraps unowned draft with its own draft", () => {661 produce({a: {}}, parent => {662 produce({a: parent.a}, child => {663 expect(child.a).not.toBe(parent.a)664 expect(isDraft(child.a)).toBeTruthy()665 expect(original(child.a)).toBe(parent.a)666 })667 })668 })669670 it("returns unowned draft if no changes were made", () => {671 produce({a: {}}, parent => {672 const result = produce({a: parent.a}, () => {})673 expect(result.a).toBe(parent.a)674 })675 })676677 it("clones the unowned draft when changes are made", () => {678 produce({a: {}}, parent => {679 const result = produce({a: parent.a}, child => {680 child.a.b = 1681 })682 expect(result.a).not.toBe(parent.a)683 expect(result.a.b).toBe(1)684 expect("b" in parent.a).toBeFalsy()685 })686 })687688 // We cannot auto-freeze the result of a nested producer,689 // because it may contain a draft from a parent producer.690 it("never auto-freezes the result", () => {691 produce({a: {}}, parent => {692 const r = produce({a: parent.a}, child => {693 child.b = 1 // Ensure a copy is returned.694 })695 expect(Object.isFrozen(r)).toBeFalsy()696 })697 })698 })699700 // "Upvalues" are variables from a parent scope.701 it("does not finalize upvalue drafts", () => {702 produce({a: {}, b: {}}, parent => {703 expect(produce({}, () => parent)).toBe(parent)704 parent.x // Ensure proxy not revoked.705706 expect(produce({}, () => [parent])[0]).toBe(parent)707 parent.x // Ensure proxy not revoked.708709 expect(produce({}, () => parent.a)).toBe(parent.a)710 parent.a.x // Ensure proxy not revoked.711712 // Modified parent test713 parent.c = 1714 expect(produce({}, () => [parent.b])[0]).toBe(parent.b)715 parent.b.x // Ensure proxy not revoked.716 })717 })718719 it("works with interweaved Immer instances", () => {720 const options = {useProxies, autoFreeze}721 const one = createPatchedImmer(options)722 const two = createPatchedImmer(options)723724 const base = {}725 const result = one.produce(base, s1 =>726 two.produce({s1}, s2 => {727 expect(original(s2.s1)).toBe(s1)728 s2.n = 1729 s2.s1 = one.produce({s2}, s3 => {730 expect(original(s3.s2)).toBe(s2)731 expect(original(s3.s2.s1)).toBe(s2.s1)732 return s3.s2.s1733 })734 })735 )736 expect(result.n).toBe(1)737 expect(result.s1).toBe(base)738 })739 })740741 if (useProxies)742 it("throws when Object.setPrototypeOf() is used on a draft", () => {743 produce({}, draft => {744 expect(() =>745 Object.setPrototypeOf(draft, Array)746 ).toThrowErrorMatchingSnapshot()747 })748 })749750 it("supports the 'in' operator", () => {751 produce(baseState, draft => {752 // Known property753 expect("anArray" in draft).toBe(true)754 expect(Reflect.has(draft, "anArray")).toBe(true)755756 // Unknown property757 expect("bla" in draft).toBe(false)758 expect(Reflect.has(draft, "bla")).toBe(false)759760 // Known index761 expect(0 in draft.anArray).toBe(true)762 expect("0" in draft.anArray).toBe(true)763 expect(Reflect.has(draft.anArray, 0)).toBe(true)764 expect(Reflect.has(draft.anArray, "0")).toBe(true)765766 // Unknown index767 expect(17 in draft.anArray).toBe(false)768 expect("17" in draft.anArray).toBe(false)769 expect(Reflect.has(draft.anArray, 17)).toBe(false)770 expect(Reflect.has(draft.anArray, "17")).toBe(false)771 })772 })773774 it("'this' should not be bound anymore - 1", () => {775 const base = {x: 3}776 const next1 = produce(base, function() {777 expect(this).toBe(undefined)778 })779 })780781 it("'this' should not be bound anymore - 2", () => {782 const incrementor = produce(function() {783 expect(this).toBe(undefined)784 })785 incrementor()786 })787788 it("should be possible to use dynamic bound this", () => {789 const world = {790 counter: {count: 1},791 inc: produce(function(draft) {792 expect(this).toBe(world)793 draft.counter.count = this.counter.count + 1794 })795 }796797 expect(world.inc(world).counter.count).toBe(2)798 })799800 // See here: https://github.com/mweststrate/immer/issues/89801 it("supports the spread operator", () => {802 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}803 const result = produce(base, draft => {804 draft.foo = {x: 1, ...draft.foo, y: 1}805 draft.bar = [1, ...draft.bar, 1]806 })807 expect(result).toEqual({808 foo: {x: 0, y: 1},809 bar: [1, 0, 0, 1]810 })811 })812813 it("processes with lodash.set", () => {814 const base = [{id: 1, a: 1}]815 const result = produce(base, draft => {816 lodash.set(draft, "[0].a", 2)817 })818 expect(base[0].a).toEqual(1)819 expect(result[0].a).toEqual(2)820 })821822 it("processes with lodash.find", () => {823 const base = [{id: 1, a: 1}]824 const result = produce(base, draft => {825 const obj1 = lodash.find(draft, {id: 1})826 lodash.set(obj1, "a", 2)827 })828 expect(base[0].a).toEqual(1)829 expect(result[0].a).toEqual(2)830 })831832 describe("recipe functions", () => {833 it("can return a new object", () => {834 const base = {x: 3}835 const res = produce(base, d => {836 return {x: d.x + 1}837 })838 expect(res).not.toBe(base)839 expect(res).toEqual({x: 4})840 })841842 it("can return the draft", () => {843 const base = {x: 3}844 const res = produce(base, d => {845 d.x = 4846 return d847 })848 expect(res).not.toBe(base)849 expect(res).toEqual({x: 4})850 })851852 it("can return an unmodified child draft", () => {853 const base = {a: {}}854 const res = produce(base, d => {855 return d.a856 })857 expect(res).toBe(base.a)858 })859860 // TODO: Avoid throwing if only the child draft was modified.861 it("cannot return a modified child draft", () => {862 const base = {a: {}}863 expect(() => {864 produce(base, d => {865 d.a.b = 1866 return d.a867 })868 }).toThrowErrorMatchingSnapshot()869 })870871 it("can return a frozen object", () => {872 const res = deepFreeze([{x: 3}])873 expect(produce({}, () => res)).toBe(res)874 })875876 it("can return an object with two references to another object", () => {877 const next = produce({}, d => {878 const obj = {}879 return {obj, arr: [obj]}880 })881 expect(next.obj).toBe(next.arr[0])882 })883884 it("can return an object with two references to an unmodified draft", () => {885 const base = {a: {}}886 const next = produce(base, d => {887 return [d.a, d.a]888 })889 expect(next[0]).toBe(base.a)890 expect(next[0]).toBe(next[1])891 })892893 it("cannot return an object that references itself", () => {894 const res = {}895 res.self = res896 expect(() => {897 produce(res, () => res.self)898 }).toThrowErrorMatchingSnapshot()899 })900 })901902 describe("async recipe function", () => {903 it("can modify the draft", () => {904 const base = {a: 0, b: 0}905 return produce(base, async d => {906 d.a = 1907 await Promise.resolve()908 d.b = 1909 }).then(res => {910 expect(res).not.toBe(base)911 expect(res).toEqual({a: 1, b: 1})912 })913 })914915 it("works with rejected promises", () => {916 let draft917 const base = {a: 0, b: 0}918 const err = new Error("passed")919 return produce(base, d => {920 draft = d921 draft.b = 1922 return Promise.reject(err)923 }).then(924 () => {925 throw "failed"926 },927 e => {928 expect(e).toBe(err)929 expect(() => draft.a).toThrowErrorMatchingSnapshot()930 }931 )932 })933934 it("supports recursive produce calls after await", () => {935 const base = {obj: {k: 1}}936 return produce(base, d => {937 const obj = d.obj938 delete d.obj939 return Promise.resolve().then(() => {940 d.a = produce({}, d => {941 d.b = obj // Assign a draft owned by the parent scope.942 })943944 // Auto-freezing is prevented when an unowned draft exists.945 expect(Object.isFrozen(d.a)).toBeFalsy()946947 // Ensure `obj` is not revoked.948 obj.c = 1949 })950 }).then(res => {951 expect(res).not.toBe(base)952 expect(res).toEqual({953 a: {b: {k: 1, c: 1}}954 })955 })956 })957 })958959 it("throws when the draft is modified and another object is returned", () => {960 const base = {x: 3}961 expect(() => {962 produce(base, draft => {963 draft.x = 4964 return {x: 5}965 })966 }).toThrowErrorMatchingSnapshot()967 })968969 it("should fix #117 - 1", () => {970 const reducer = (state, action) =>971 produce(state, draft => {972 switch (action.type) {973 case "SET_STARTING_DOTS":974 return draft.availableStartingDots.map(a => a)975 default:976 break977 }978 })979 const base = {980 availableStartingDots: [981 {dots: 4, count: 1},982 {dots: 3, count: 2},983 {dots: 2, count: 3},984 {dots: 1, count: 4}985 ]986 }987 const next = reducer(base, {type: "SET_STARTING_DOTS"})988 expect(next).toEqual(base.availableStartingDots)989 expect(next).not.toBe(base.availableStartingDots)990 })991992 it("should fix #117 - 2", () => {993 const reducer = (state, action) =>994 produce(state, draft => {995 switch (action.type) {996 case "SET_STARTING_DOTS":997 return {998 dots: draft.availableStartingDots.map(a => a)999 }1000 default:1001 break1002 }1003 })1004 const base = {1005 availableStartingDots: [1006 {dots: 4, count: 1},1007 {dots: 3, count: 2},1008 {dots: 2, count: 3},1009 {dots: 1, count: 4}1010 ]1011 }1012 const next = reducer(base, {type: "SET_STARTING_DOTS"})1013 expect(next).toEqual({dots: base.availableStartingDots})1014 })10151016 it("cannot always detect noop assignments - 0", () => {1017 const baseState = {x: {y: 3}}1018 const nextState = produce(baseState, d => {1019 const a = d.x1020 d.x = a1021 })1022 expect(nextState).toBe(baseState)1023 })10241025 it("cannot always detect noop assignments - 1", () => {1026 const baseState = {x: {y: 3}}1027 const nextState = produce(baseState, d => {1028 const a = d.x1029 d.x = 41030 d.x = a1031 })1032 // Ideally, this should actually be the same instances1033 // but this would be pretty expensive to detect,1034 // so we don't atm1035 expect(nextState).not.toBe(baseState)1036 })10371038 it("cannot always detect noop assignments - 2", () => {1039 const baseState = {x: {y: 3}}1040 const nextState = produce(baseState, d => {1041 const a = d.x1042 const stuff = a.y + 31043 d.x = 41044 d.x = a1045 })1046 // Ideally, this should actually be the same instances1047 // but this would be pretty expensive to detect,1048 // so we don't atm1049 expect(nextState).not.toBe(baseState)1050 })10511052 it("cannot always detect noop assignments - 3", () => {1053 const baseState = {x: 3}1054 const nextState = produce(baseState, d => {1055 d.x = 31056 })1057 expect(nextState).toBe(baseState)1058 })10591060 it("cannot always detect noop assignments - 4", () => {1061 const baseState = {x: 3}1062 const nextState = produce(baseState, d => {1063 d.x = 41064 d.x = 31065 })1066 // Ideally, this should actually be the same instances1067 // but this would be pretty expensive to detect,1068 // so we don't atm1069 expect(nextState).not.toBe(baseState)1070 })10711072 it("cannot produce undefined by returning undefined", () => {1073 const base = 31074 expect(produce(base, () => 4)).toBe(4)1075 expect(produce(base, () => null)).toBe(null)1076 expect(produce(base, () => undefined)).toBe(3)1077 expect(produce(base, () => {})).toBe(3)1078 expect(produce(base, () => nothing)).toBe(undefined)10791080 expect(produce({}, () => undefined)).toEqual({})1081 expect(produce({}, () => nothing)).toBe(undefined)1082 expect(produce(3, () => nothing)).toBe(undefined)10831084 expect(produce(() => undefined)({})).toEqual({})1085 expect(produce(() => nothing)({})).toBe(undefined)1086 expect(produce(() => nothing)(3)).toBe(undefined)1087 })10881089 describe("base state type", () => {1090 testObjectTypes(produce)1091 testLiteralTypes(produce)1092 })10931094 afterEach(() => {1095 expect(baseState).toBe(origBaseState)1096 expect(baseState).toEqual(createBaseState())1097 })10981099 class Foo {}1100 function createBaseState() {1101 const data = {1102 anInstance: new Foo(),1103 anArray: [3, 2, {c: 3}, 1],1104 aProp: "hi",1105 anObject: {1106 nested: {1107 yummie: true1108 },1109 coffee: false1110 }1111 }1112 return autoFreeze ? deepFreeze(data) : data1113 }1114 })11151116 describe(`isDraft - ${name}`, () => {1117 it("returns true for object drafts", () => {1118 produce({}, state => {1119 expect(isDraft(state)).toBeTruthy()1120 })1121 })1122 it("returns true for array drafts", () => {1123 produce([], state => {1124 expect(isDraft(state)).toBeTruthy()1125 })1126 })1127 it("returns true for objects nested in object drafts", () => {1128 produce({a: {b: {}}}, state => {1129 expect(isDraft(state.a)).toBeTruthy()1130 expect(isDraft(state.a.b)).toBeTruthy()1131 })1132 })1133 it("returns false for new objects added to a draft", () => {1134 produce({}, state => {1135 state.a = {}1136 expect(isDraft(state.a)).toBeFalsy()1137 })1138 })1139 it("returns false for objects returned by the producer", () => {1140 const object = produce(null, Object.create)1141 expect(isDraft(object)).toBeFalsy()1142 })1143 it("returns false for arrays returned by the producer", () => {1144 const array = produce(null, _ => [])1145 expect(isDraft(array)).toBeFalsy()1146 })1147 it("returns false for object drafts returned by the producer", () => {1148 const object = produce({}, state => state)1149 expect(isDraft(object)).toBeFalsy()1150 })1151 it("returns false for array drafts returned by the producer", () => {1152 const array = produce([], state => state)1153 expect(isDraft(array)).toBeFalsy()1154 })1155 })1156}11571158function testObjectTypes(produce) {1159 class Foo {1160 constructor(foo) {1161 this.foo = foo1162 this[immerable] = true1163 }1164 }1165 const values = {1166 "empty object": {},1167 "plain object": {a: 1, b: 2},1168 "object (no prototype)": Object.create(null),1169 "empty array": [],1170 "plain array": [1, 2],1171 "class instance (draftable)": new Foo(1)1172 }1173 for (const name in values) {1174 const value = values[name]1175 const copy = shallowCopy(value)1176 testObjectType(name, value)1177 testObjectType(name + " (frozen)", Object.freeze(copy))1178 }1179 function testObjectType(name, base) {1180 describe(name, () => {1181 it("creates a draft", () => {1182 produce(base, draft => {1183 expect(draft).not.toBe(base)1184 expect(shallowCopy(draft, true)).toEqual(base)1185 })1186 })11871188 it("preserves the prototype", () => {1189 const proto = Object.getPrototypeOf(base)1190 produce(base, draft => {1191 expect(Object.getPrototypeOf(draft)).toBe(proto)1192 })1193 })11941195 it("returns the base state when no changes are made", () => {1196 expect(produce(base, () => {})).toBe(base)1197 })11981199 it("returns a copy when changes are made", () => {1200 const random = Math.random()1201 const result = produce(base, draft => {1202 draft[0] = random1203 })1204 expect(result).not.toBe(base)1205 expect(result.constructor).toBe(base.constructor)1206 expect(result[0]).toBe(random)1207 })1208 })1209 }1210}12111212function testLiteralTypes(produce) {1213 class Foo {}1214 const values = {1215 "falsy number": 0,1216 "truthy number": 1,1217 "negative number": -1,1218 NaN: NaN,1219 infinity: 1 / 0,1220 true: true,1221 false: false,1222 "empty string": "",1223 "truthy string": "1",1224 null: null,1225 undefined: undefined,12261227 /**1228 * These objects are treated as literals because Immer1229 * does not know how to draft them.1230 */1231 function: () => {},1232 "regexp object": /.+/g,1233 "boxed number": new Number(0),1234 "boxed string": new String(""),1235 "boxed boolean": new Boolean(),1236 "date object": new Date(),1237 "class instance (not draftable)": new Foo()1238 }1239 for (const name in values) {1240 describe(name, () => {1241 const value = values[name]12421243 it("does not create a draft", () => {1244 produce(value, draft => {1245 expect(draft).toBe(value)1246 })1247 })12481249 it("returns the base state when no changes are made", () => {1250 expect(produce(value, () => {})).toBe(value)1251 })12521253 if (value && typeof value == "object") {1254 it("does not return a copy when changes are made", () => {1255 expect(1256 produce(value, draft => {1257 draft.foo = true1258 })1259 ).toBe(value)1260 })1261 }1262 })1263 }1264}12651266function enumerableOnly(x) {1267 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1268 each(copy, (prop, value) => {1269 if (value && typeof value === "object") {1270 copy[prop] = enumerableOnly(value)1271 }1272 })1273 return copy1274}