base.js
This file
Path
__tests__/base.js
1,269 lines · 44.7 KiB · JavaScript
Last changed by
test: more recursive produce testsAlec Larsonbefore adoption8adfb31
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 work - 1", () => {775 const base = {x: 3}776 const next1 = produce(base, function() {777 this.x = 4778 })779 expect(next1).not.toBe(base)780 expect(next1.x).toBe(4)781 })782783 it("'this' should work - 2", () => {784 const base = {x: 3}785 const incrementor = produce(function() {786 this.x = 4787 })788 const next1 = incrementor(base)789 expect(next1).not.toBe(base)790 expect(next1.x).toBe(4)791 })792793 // See here: https://github.com/mweststrate/immer/issues/89794 it("supports the spread operator", () => {795 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}796 const result = produce(base, draft => {797 draft.foo = {x: 1, ...draft.foo, y: 1}798 draft.bar = [1, ...draft.bar, 1]799 })800 expect(result).toEqual({801 foo: {x: 0, y: 1},802 bar: [1, 0, 0, 1]803 })804 })805806 it("processes with lodash.set", () => {807 const base = [{id: 1, a: 1}]808 const result = produce(base, draft => {809 lodash.set(draft, "[0].a", 2)810 })811 expect(base[0].a).toEqual(1)812 expect(result[0].a).toEqual(2)813 })814815 it("processes with lodash.find", () => {816 const base = [{id: 1, a: 1}]817 const result = produce(base, draft => {818 const obj1 = lodash.find(draft, {id: 1})819 lodash.set(obj1, "a", 2)820 })821 expect(base[0].a).toEqual(1)822 expect(result[0].a).toEqual(2)823 })824825 describe("recipe functions", () => {826 it("can return a new object", () => {827 const base = {x: 3}828 const res = produce(base, d => {829 return {x: d.x + 1}830 })831 expect(res).not.toBe(base)832 expect(res).toEqual({x: 4})833 })834835 it("can return the draft", () => {836 const base = {x: 3}837 const res = produce(base, d => {838 d.x = 4839 return d840 })841 expect(res).not.toBe(base)842 expect(res).toEqual({x: 4})843 })844845 it("can return an unmodified child draft", () => {846 const base = {a: {}}847 const res = produce(base, d => {848 return d.a849 })850 expect(res).toBe(base.a)851 })852853 // TODO: Avoid throwing if only the child draft was modified.854 it("cannot return a modified child draft", () => {855 const base = {a: {}}856 expect(() => {857 produce(base, d => {858 d.a.b = 1859 return d.a860 })861 }).toThrowErrorMatchingSnapshot()862 })863864 it("can return a frozen object", () => {865 const res = deepFreeze([{x: 3}])866 expect(produce({}, () => res)).toBe(res)867 })868869 it("can return an object with two references to another object", () => {870 const next = produce({}, d => {871 const obj = {}872 return {obj, arr: [obj]}873 })874 expect(next.obj).toBe(next.arr[0])875 })876877 it("can return an object with two references to an unmodified draft", () => {878 const base = {a: {}}879 const next = produce(base, d => {880 return [d.a, d.a]881 })882 expect(next[0]).toBe(base.a)883 expect(next[0]).toBe(next[1])884 })885886 it("cannot return an object that references itself", () => {887 const res = {}888 res.self = res889 expect(() => {890 produce(res, () => res.self)891 }).toThrowErrorMatchingSnapshot()892 })893 })894895 // TODO: rewrite tests with async/await once node 6 support is dropped896 describe("async recipe function", () => {897 it("can modify the draft", () => {898 const base = {a: 0, b: 0}899 return produce(base, d => {900 d.a = 1901 return Promise.resolve().then(() => {902 d.b = 1903 })904 }).then(res => {905 expect(res).not.toBe(base)906 expect(res).toEqual({a: 1, b: 1})907 })908 })909910 it("works with rejected promises", () => {911 let draft912 const base = {a: 0, b: 0}913 const err = new Error("passed")914 return produce(base, d => {915 draft = d916 draft.b = 1917 return Promise.reject(err)918 }).then(919 () => {920 throw "failed"921 },922 e => {923 expect(e).toBe(err)924 expect(() => draft.a).toThrowErrorMatchingSnapshot()925 }926 )927 })928929 it("supports recursive produce calls after await", () => {930 const base = {obj: {k: 1}}931 return produce(base, d => {932 const obj = d.obj933 delete d.obj934 return Promise.resolve().then(() => {935 d.a = produce({}, d => {936 d.b = obj // Assign a draft owned by the parent scope.937 })938939 // Auto-freezing is prevented when an unowned draft exists.940 expect(Object.isFrozen(d.a)).toBeFalsy()941942 // Ensure `obj` is not revoked.943 obj.c = 1944 })945 }).then(res => {946 expect(res).not.toBe(base)947 expect(res).toEqual({948 a: {b: {k: 1, c: 1}}949 })950 })951 })952 })953954 it("throws when the draft is modified and another object is returned", () => {955 const base = {x: 3}956 expect(() => {957 produce(base, draft => {958 draft.x = 4959 return {x: 5}960 })961 }).toThrowErrorMatchingSnapshot()962 })963964 it("should fix #117 - 1", () => {965 const reducer = (state, action) =>966 produce(state, draft => {967 switch (action.type) {968 case "SET_STARTING_DOTS":969 return draft.availableStartingDots.map(a => a)970 default:971 break972 }973 })974 const base = {975 availableStartingDots: [976 {dots: 4, count: 1},977 {dots: 3, count: 2},978 {dots: 2, count: 3},979 {dots: 1, count: 4}980 ]981 }982 const next = reducer(base, {type: "SET_STARTING_DOTS"})983 expect(next).toEqual(base.availableStartingDots)984 expect(next).not.toBe(base.availableStartingDots)985 })986987 it("should fix #117 - 2", () => {988 const reducer = (state, action) =>989 produce(state, draft => {990 switch (action.type) {991 case "SET_STARTING_DOTS":992 return {993 dots: draft.availableStartingDots.map(a => a)994 }995 default:996 break997 }998 })999 const base = {1000 availableStartingDots: [1001 {dots: 4, count: 1},1002 {dots: 3, count: 2},1003 {dots: 2, count: 3},1004 {dots: 1, count: 4}1005 ]1006 }1007 const next = reducer(base, {type: "SET_STARTING_DOTS"})1008 expect(next).toEqual({dots: base.availableStartingDots})1009 })10101011 it("cannot always detect noop assignments - 0", () => {1012 const baseState = {x: {y: 3}}1013 const nextState = produce(baseState, d => {1014 const a = d.x1015 d.x = a1016 })1017 expect(nextState).toBe(baseState)1018 })10191020 it("cannot always detect noop assignments - 1", () => {1021 const baseState = {x: {y: 3}}1022 const nextState = produce(baseState, d => {1023 const a = d.x1024 d.x = 41025 d.x = a1026 })1027 // Ideally, this should actually be the same instances1028 // but this would be pretty expensive to detect,1029 // so we don't atm1030 expect(nextState).not.toBe(baseState)1031 })10321033 it("cannot always detect noop assignments - 2", () => {1034 const baseState = {x: {y: 3}}1035 const nextState = produce(baseState, d => {1036 const a = d.x1037 const stuff = a.y + 31038 d.x = 41039 d.x = a1040 })1041 // Ideally, this should actually be the same instances1042 // but this would be pretty expensive to detect,1043 // so we don't atm1044 expect(nextState).not.toBe(baseState)1045 })10461047 it("cannot always detect noop assignments - 3", () => {1048 const baseState = {x: 3}1049 const nextState = produce(baseState, d => {1050 d.x = 31051 })1052 expect(nextState).toBe(baseState)1053 })10541055 it("cannot always detect noop assignments - 4", () => {1056 const baseState = {x: 3}1057 const nextState = produce(baseState, d => {1058 d.x = 41059 d.x = 31060 })1061 // Ideally, this should actually be the same instances1062 // but this would be pretty expensive to detect,1063 // so we don't atm1064 expect(nextState).not.toBe(baseState)1065 })10661067 it("cannot produce undefined by returning undefined", () => {1068 const base = 31069 expect(produce(base, () => 4)).toBe(4)1070 expect(produce(base, () => null)).toBe(null)1071 expect(produce(base, () => undefined)).toBe(3)1072 expect(produce(base, () => {})).toBe(3)1073 expect(produce(base, () => nothing)).toBe(undefined)10741075 expect(produce({}, () => undefined)).toEqual({})1076 expect(produce({}, () => nothing)).toBe(undefined)1077 expect(produce(3, () => nothing)).toBe(undefined)10781079 expect(produce(() => undefined)({})).toEqual({})1080 expect(produce(() => nothing)({})).toBe(undefined)1081 expect(produce(() => nothing)(3)).toBe(undefined)1082 })10831084 describe("base state type", () => {1085 testObjectTypes(produce)1086 testLiteralTypes(produce)1087 })10881089 afterEach(() => {1090 expect(baseState).toBe(origBaseState)1091 expect(baseState).toEqual(createBaseState())1092 })10931094 class Foo {}1095 function createBaseState() {1096 const data = {1097 anInstance: new Foo(),1098 anArray: [3, 2, {c: 3}, 1],1099 aProp: "hi",1100 anObject: {1101 nested: {1102 yummie: true1103 },1104 coffee: false1105 }1106 }1107 return autoFreeze ? deepFreeze(data) : data1108 }1109 })11101111 describe(`isDraft - ${name}`, () => {1112 it("returns true for object drafts", () => {1113 produce({}, state => {1114 expect(isDraft(state)).toBeTruthy()1115 })1116 })1117 it("returns true for array drafts", () => {1118 produce([], state => {1119 expect(isDraft(state)).toBeTruthy()1120 })1121 })1122 it("returns true for objects nested in object drafts", () => {1123 produce({a: {b: {}}}, state => {1124 expect(isDraft(state.a)).toBeTruthy()1125 expect(isDraft(state.a.b)).toBeTruthy()1126 })1127 })1128 it("returns false for new objects added to a draft", () => {1129 produce({}, state => {1130 state.a = {}1131 expect(isDraft(state.a)).toBeFalsy()1132 })1133 })1134 it("returns false for objects returned by the producer", () => {1135 const object = produce(null, Object.create)1136 expect(isDraft(object)).toBeFalsy()1137 })1138 it("returns false for arrays returned by the producer", () => {1139 const array = produce(null, _ => [])1140 expect(isDraft(array)).toBeFalsy()1141 })1142 it("returns false for object drafts returned by the producer", () => {1143 const object = produce({}, state => state)1144 expect(isDraft(object)).toBeFalsy()1145 })1146 it("returns false for array drafts returned by the producer", () => {1147 const array = produce([], state => state)1148 expect(isDraft(array)).toBeFalsy()1149 })1150 })1151}11521153function testObjectTypes(produce) {1154 class Foo {1155 constructor(foo) {1156 this.foo = foo1157 this[immerable] = true1158 }1159 }1160 const values = {1161 "empty object": {},1162 "plain object": {a: 1, b: 2},1163 "object (no prototype)": Object.create(null),1164 "empty array": [],1165 "plain array": [1, 2],1166 "class instance (draftable)": new Foo(1)1167 }1168 for (const name in values) {1169 const value = values[name]1170 const copy = shallowCopy(value)1171 testObjectType(name, value)1172 testObjectType(name + " (frozen)", Object.freeze(copy))1173 }1174 function testObjectType(name, base) {1175 describe(name, () => {1176 it("creates a draft", () => {1177 produce(base, draft => {1178 expect(draft).not.toBe(base)1179 expect(shallowCopy(draft, true)).toEqual(base)1180 })1181 })11821183 it("preserves the prototype", () => {1184 const proto = Object.getPrototypeOf(base)1185 produce(base, draft => {1186 expect(Object.getPrototypeOf(draft)).toBe(proto)1187 })1188 })11891190 it("returns the base state when no changes are made", () => {1191 expect(produce(base, () => {})).toBe(base)1192 })11931194 it("returns a copy when changes are made", () => {1195 const random = Math.random()1196 const result = produce(base, draft => {1197 draft[0] = random1198 })1199 expect(result).not.toBe(base)1200 expect(result.constructor).toBe(base.constructor)1201 expect(result[0]).toBe(random)1202 })1203 })1204 }1205}12061207function testLiteralTypes(produce) {1208 class Foo {}1209 const values = {1210 "falsy number": 0,1211 "truthy number": 1,1212 "negative number": -1,1213 NaN: NaN,1214 infinity: 1 / 0,1215 true: true,1216 false: false,1217 "empty string": "",1218 "truthy string": "1",1219 null: null,1220 undefined: undefined,12211222 /**1223 * These objects are treated as literals because Immer1224 * does not know how to draft them.1225 */1226 function: () => {},1227 "regexp object": /.+/g,1228 "boxed number": new Number(0),1229 "boxed string": new String(""),1230 "boxed boolean": new Boolean(),1231 "date object": new Date(),1232 "class instance (not draftable)": new Foo()1233 }1234 for (const name in values) {1235 describe(name, () => {1236 const value = values[name]12371238 it("does not create a draft", () => {1239 produce(value, draft => {1240 expect(draft).toBe(value)1241 })1242 })12431244 it("returns the base state when no changes are made", () => {1245 expect(produce(value, () => {})).toBe(value)1246 })12471248 if (value && typeof value == "object") {1249 it("does not return a copy when changes are made", () => {1250 expect(1251 produce(value, draft => {1252 draft.foo = true1253 })1254 ).toBe(value)1255 })1256 }1257 })1258 }1259}12601261function enumerableOnly(x) {1262 const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1263 each(copy, (prop, value) => {1264 if (value && typeof value === "object") {1265 copy[prop] = enumerableOnly(value)1266 }1267 })1268 return copy1269}