Skip to content
Myr

base.js

This file

Path

__tests__/base.js

1,151 lines · 40.5 KiB · JavaScript

Last changed by

test: improve "nested producer" testsaleclarsonbefore adoptionf9cd736

History of this file

Take 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        it("can get property descriptors", () => {114            const getDescriptor = Object.getOwnPropertyDescriptor115            const baseState = deepFreeze([{a: 1}])116            produce(baseState, arr => {117                const obj = arr[0]118                const desc = {119                    configurable: true,120                    enumerable: true,121                    ...(useProxies && {writable: true})122                }123124                // Known property125                expect(getDescriptor(obj, "a")).toMatchObject(desc)126                expect(getDescriptor(arr, 0)).toMatchObject(desc)127128                // Deleted property129                delete obj.a130                arr.pop()131                expect(getDescriptor(obj, "a")).toBeUndefined()132                expect(getDescriptor(arr, 0)).toBeUndefined()133134                // Unknown property135                expect(getDescriptor(obj, "b")).toBeUndefined()136                expect(getDescriptor(arr, 100)).toBeUndefined()137138                // Added property139                obj.b = 2140                arr[100] = 1141                expect(getDescriptor(obj, "b")).toBeDefined()142                expect(getDescriptor(arr, 100)).toBeDefined()143            })144        })145146        describe("array drafts", () => {147            it("supports Array.isArray()", () => {148                const nextState = produce(baseState, s => {149                    expect(Array.isArray(s.anArray)).toBeTruthy()150                    s.anArray.push(1)151                })152                expect(Array.isArray(nextState.anArray)).toBeTruthy()153            })154155            it("supports index access", () => {156                const value = baseState.anArray[0]157                const nextState = produce(baseState, s => {158                    expect(s.anArray[0]).toBe(value)159                })160                expect(nextState).toBe(baseState)161            })162163            it("supports iteration", () => {164                const base = [{id: 1, a: 1}, {id: 2, a: 1}]165                const findById = (collection, id) => {166                    for (const item of collection) {167                        if (item.id === id) return item168                    }169                    return null170                }171                const result = produce(base, draft => {172                    const obj1 = findById(draft, 1)173                    const obj2 = findById(draft, 2)174                    obj1.a = 2175                    obj2.a = 2176                })177                expect(result[0].a).toEqual(2)178                expect(result[1].a).toEqual(2)179            })180181            it("can assign an index via bracket notation", () => {182                const nextState = produce(baseState, s => {183                    s.anArray[3] = true184                })185                expect(nextState).not.toBe(baseState)186                expect(nextState.anArray).not.toBe(baseState.anArray)187                expect(nextState.anArray[3]).toEqual(true)188            })189190            it("can use splice() to both add and remove items", () => {191                const nextState = produce(baseState, s => {192                    s.anArray.splice(1, 1, "a", "b")193                })194                expect(nextState.anArray).not.toBe(baseState.anArray)195                expect(nextState.anArray[1]).toBe("a")196                expect(nextState.anArray[2]).toBe("b")197            })198199            it("can truncate via the length property", () => {200                const baseLength = baseState.anArray.length201                const nextState = produce(baseState, s => {202                    s.anArray.length = baseLength - 1203                })204                expect(nextState.anArray).not.toBe(baseState.anArray)205                expect(nextState.anArray.length).toBe(baseLength - 1)206            })207208            it("can extend via the length property", () => {209                const baseLength = baseState.anArray.length210                const nextState = produce(baseState, s => {211                    s.anArray.length = baseLength + 1212                })213                expect(nextState.anArray).not.toBe(baseState.anArray)214                expect(nextState.anArray.length).toBe(baseLength + 1)215            })216217            // Reported here: https://github.com/mweststrate/immer/issues/116218            it("can pop then push", () => {219                const nextState = produce([1, 2, 3], s => {220                    s.pop()221                    s.push(100)222                })223                expect(nextState).toEqual([1, 2, 100])224            })225226            it("can be sorted", () => {227                const baseState = [3, 1, 2]228                const nextState = produce(baseState, s => {229                    s.sort()230                })231                expect(nextState).not.toBe(baseState)232                expect(nextState).toEqual([1, 2, 3])233            })234235            it("supports modifying nested objects", () => {236                const baseState = [{a: 1}, {}]237                const nextState = produce(baseState, s => {238                    s[0].a++239                    s[1].a = 0240                })241                expect(nextState).not.toBe(baseState)242                expect(nextState[0].a).toBe(2)243                expect(nextState[1].a).toBe(0)244            })245246            it("never preserves non-numeric properties", () => {247                const baseState = []248                baseState.x = 7249                const nextState = produce(baseState, s => {250                    s.push(3)251                })252                expect("x" in nextState).toBeFalsy()253            })254255            if (useProxies) {256                it("throws when a non-numeric property is added", () => {257                    expect(() => {258                        produce([], d => {259                            d.x = 3260                        })261                    }).toThrow(262                        "Immer only supports setting array indices and the 'length' property"263                    )264                })265266                it("throws when a non-numeric property is deleted", () => {267                    expect(() => {268                        const baseState = []269                        baseState.x = 7270                        produce(baseState, d => {271                            delete d.x272                        })273                    }).toThrow("Immer only supports deleting array indices")274                })275            }276        })277278        it("supports `immerable` symbol on constructor", () => {279            class One {}280            One[immerable] = true281            const baseState = new One()282            const nextState = produce(baseState, draft => {283                expect(draft).not.toBe(baseState)284                draft.foo = true285            })286            expect(nextState).not.toBe(baseState)287            expect(nextState.foo).toBeTruthy()288        })289290        it("preserves symbol properties", () => {291            const test = Symbol("test")292            const baseState = {[test]: true}293            const nextState = produce(baseState, s => {294                expect(s[test]).toBeTruthy()295                s.foo = true296            })297            expect(nextState).toEqual({298                [test]: true,299                foo: true300            })301        })302303        it("preserves non-enumerable properties", () => {304            const baseState = {}305            // Non-enumerable object property306            Object.defineProperty(baseState, "foo", {307                value: {a: 1},308                enumerable: false309            })310            // Non-enumerable primitive property311            Object.defineProperty(baseState, "bar", {312                value: 1,313                enumerable: false314            })315            const nextState = produce(baseState, s => {316                expect(s.foo).toBeTruthy()317                expect(isEnumerable(s, "foo")).toBeFalsy()318                s.bar++319                expect(isEnumerable(s, "foo")).toBeFalsy()320                s.foo.a++321                expect(isEnumerable(s, "foo")).toBeFalsy()322            })323            expect(nextState.foo).toBeTruthy()324            expect(isEnumerable(nextState, "foo")).toBeFalsy()325        })326327        it("throws on computed properties", () => {328            const baseState = {}329            Object.defineProperty(baseState, "foo", {330                get: () => {},331                enumerable: true332            })333            expect(() => {334                produce(baseState, s => {335                    // Proxies only throw once a change is made.336                    if (useProxies) {337                        s.modified = true338                    }339                })340            }).toThrowError("Immer drafts cannot have computed properties")341        })342343        it("allows inherited computed properties", () => {344            const proto = {}345            Object.defineProperty(proto, "foo", {346                get() {347                    return this.bar348                },349                set(val) {350                    this.bar = val351                }352            })353            const baseState = Object.create(proto)354            produce(baseState, s => {355                expect(s.bar).toBeUndefined()356                s.foo = {}357                expect(s.bar).toBeDefined()358                expect(s.foo).toBe(s.bar)359            })360        })361362        it("supports a base state with multiple references to an object", () => {363            const obj = {}364            const res = produce({a: obj, b: obj}, d => {365                // Two drafts are created for each occurrence of an object in the base state.366                expect(d.a).not.toBe(d.b)367                d.a.z = true368                expect(d.b.z).toBeUndefined()369            })370            expect(res.b).toBe(obj)371            expect(res.a).not.toBe(res.b)372            expect(res.a.z).toBeTruthy()373        })374375        // NOTE: Except the root draft.376        it("supports multiple references to any modified draft", () => {377            const next = produce({a: {b: 1}}, d => {378                d.a.b++379                d.b = d.a380            })381            expect(next.a).toBe(next.b)382        })383384        it("can rename nested objects (no changes)", () => {385            const nextState = produce({obj: {}}, s => {386                s.foo = s.obj387                delete s.obj388            })389            expect(nextState).toEqual({foo: {}})390        })391392        // Very similar to the test before, but the reused object has one393        // property changed, one added, and one removed.394        it("can rename nested objects (with changes)", () => {395            const nextState = produce({obj: {a: 1, b: 1}}, s => {396                s.obj.a = true // change397                delete s.obj.b // delete398                s.obj.c = true // add399400                s.foo = s.obj401                delete s.obj402            })403            expect(nextState).toEqual({foo: {a: true, c: true}})404        })405406        it("can nest a draft in a new object (no changes)", () => {407            const baseState = {obj: {}}408            const nextState = produce(baseState, s => {409                s.foo = {bar: s.obj}410                delete s.obj411            })412            expect(nextState.foo.bar).toBe(baseState.obj)413        })414415        it("can nest a modified draft in a new object", () => {416            const nextState = produce({obj: {a: 1, b: 1}}, s => {417                s.obj.a = true // change418                delete s.obj.b // delete419                s.obj.c = true // add420421                s.foo = {bar: s.obj}422                delete s.obj423            })424            expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})425        })426427        it("supports assigning undefined to an existing property", () => {428            const nextState = produce(baseState, s => {429                s.aProp = undefined430            })431            expect(nextState).not.toBe(baseState)432            expect(nextState.aProp).toBe(undefined)433        })434435        it("supports assigning undefined to a new property", () => {436            const baseState = {}437            const nextState = produce(baseState, s => {438                s.aProp = undefined439            })440            expect(nextState).not.toBe(baseState)441            expect(nextState.aProp).toBe(undefined)442        })443444        // NOTE: ES5 drafts only protect existing properties when revoked.445        it("revokes the draft once produce returns", () => {446            const expectRevoked = (fn, shouldThrow = true) => {447                if (shouldThrow) expect(fn).toThrowError(/revoked/)448                else expect(fn).not.toThrow()449            }450451            // Test object drafts:452            let draft453            produce({a: 1, b: 1}, s => {454                draft = s455                delete s.b456            })457458            // Access known property on object draft.459            expectRevoked(() => {460                draft.a461            })462463            // Assign known property on object draft.464            expectRevoked(() => {465                draft.a = true466            })467468            // Access unknown property on object draft.469            expectRevoked(() => {470                draft.z471            }, useProxies)472473            // Assign unknown property on object draft.474            expectRevoked(() => {475                draft.z = true476            }, useProxies)477478            // Test array drafts:479            produce([1, 2], s => {480                draft = s481                s.pop()482            })483484            // Access known index of an array draft.485            expectRevoked(() => {486                draft[0]487            })488489            // Assign known index of an array draft.490            expectRevoked(() => {491                draft[0] = true492            })493494            // Access unknown index of an array draft.495            expectRevoked(() => {496                draft[1]497            }, useProxies)498499            // Assign unknown index of an array draft.500            expectRevoked(() => {501                draft[1] = true502            }, useProxies)503        })504505        it("can access a child draft that was created before the draft was modified", () => {506            produce({a: {}}, s => {507                const before = s.a508                s.b = 1509                expect(s.a).toBe(before)510            })511        })512513        it("should reflect all changes made in the draft immediately", () => {514            produce(baseState, draft => {515                draft.anArray[0] = 5516                draft.anArray.unshift("test")517                expect(enumerableOnly(draft.anArray)).toEqual([518                    "test",519                    5,520                    2,521                    {c: 3},522                    1523                ])524                draft.stuffz = "coffee"525                expect(draft.stuffz).toBe("coffee")526            })527        })528529        if (useProxies)530            it("throws when Object.defineProperty() is used on drafts", () => {531                expect(() => {532                    produce({}, draft => {533                        Object.defineProperty(draft, "xx", {534                            enumerable: true,535                            writeable: true,536                            value: 2537                        })538                    })539                }).toThrow(540                    "Object.defineProperty() cannot be used on an Immer draft"541                )542            })543544        it("should handle constructor correctly", () => {545            const baseState = {546                arr: new Array(),547                obj: new Object()548            }549            const result = produce(baseState, draft => {550                draft.arrConstructed = draft.arr.constructor(1)551                draft.objConstructed = draft.obj.constructor(1)552            })553            expect(result.arrConstructed).toEqual(new Array().constructor(1))554            expect(result.objConstructed).toEqual(new Object().constructor(1))555        })556557        it("should handle equality correctly - 1", () => {558            const baseState = {559                y: 3 / 0,560                z: NaN561            }562            const nextState = produce(baseState, draft => {563                draft.y = 4 / 0564                draft.z = NaN565            })566            expect(nextState).toBe(baseState)567        })568569        it("should handle equality correctly - 2", () => {570            const baseState = {571                x: -0572            }573            const nextState = produce(baseState, draft => {574                draft.x = +0575            })576            expect(nextState).not.toBe(baseState)577            expect(nextState).not.toEqual(baseState)578        })579580        // AKA: recursive produce calls581        describe("nested producers", () => {582            describe("when base state is not a draft", () => {583                // This test ensures the global state used to manage proxies is584                // never left in a corrupted state by a nested `produce` call.585                it("never affects its parent producer implicitly", () => {586                    const base = {obj: {a: 1}}587                    const next = produce(base, draft => {588                        // Notice how `base.obj` is passed, not `draft.obj`589                        const obj2 = produce(base.obj, draft2 => {590                            draft2.a = 0591                        })592                        expect(obj2.a).toBe(0)593                        expect(draft.obj.a).toBe(1) // effects should not be visible outside594                    })595                    expect(next).toBe(base)596                })597            })598599            describe("when base state is a draft", () => {600                it("always wraps the draft in a new draft", () => {601                    produce({}, parent => {602                        produce(parent, child => {603                            expect(child).not.toBe(parent)604                            expect(isDraft(child)).toBeTruthy()605                            expect(original(child)).toBe(parent)606                        })607                    })608                })609            })610611            describe("when base state contains a draft", () => {612                it("wraps unowned draft with its own draft", () => {613                    produce({a: {}}, parent => {614                        produce({a: parent.a}, child => {615                            expect(child.a).not.toBe(parent.a)616                            expect(isDraft(child.a)).toBeTruthy()617                            expect(original(child.a)).toBe(parent.a)618                        })619                    })620                })621622                it("returns unowned draft if no changes were made", () => {623                    produce({a: {}}, parent => {624                        const result = produce({a: parent.a}, () => {})625                        expect(result.a).toBe(parent.a)626                    })627                })628629                it("clones the unowned draft when changes are made", () => {630                    produce({a: {}}, parent => {631                        const result = produce({a: parent.a}, child => {632                            child.a.b = 1633                        })634                        expect(result.a).not.toBe(parent.a)635                        expect(result.a.b).toBe(1)636                        expect("b" in parent.a).toBeFalsy()637                    })638                })639640                // We cannot auto-freeze the result of a nested producer,641                // because it may contain a draft from a parent producer.642                it("never auto-freezes the result", () => {643                    produce({a: {}}, parent => {644                        const r = produce({a: parent.a}, child => {645                            child.b = 1 // Ensure a copy is returned.646                        })647                        expect(Object.isFrozen(r)).toBeFalsy()648                    })649                })650            })651652            // "Upvalues" are variables from a parent scope.653            it("does not finalize upvalue drafts", () => {654                produce({a: {}, b: {}}, parent => {655                    expect(produce({}, () => parent)).toBe(parent)656                    parent.x // Ensure proxy not revoked.657658                    expect(produce({}, () => [parent])[0]).toBe(parent)659                    parent.x // Ensure proxy not revoked.660661                    expect(produce({}, () => parent.a)).toBe(parent.a)662                    parent.a.x // Ensure proxy not revoked.663664                    // Modified parent test665                    parent.c = 1666                    expect(produce({}, () => [parent.b])[0]).toBe(parent.b)667                    parent.b.x // Ensure proxy not revoked.668                })669            })670671            it("works with interweaved Immer instances", () => {672                const options = {useProxies, autoFreeze}673                const one = createPatchedImmer(options)674                const two = createPatchedImmer(options)675676                const base = {}677                const result = one.produce(base, s1 =>678                    two.produce({s1}, s2 => {679                        expect(original(s2.s1)).toBe(s1)680                        s2.n = 1681                        s2.s1 = one.produce({s2}, s3 => {682                            expect(original(s3.s2)).toBe(s2)683                            expect(original(s3.s2.s1)).toBe(s2.s1)684                            return s3.s2.s1685                        })686                    })687                )688                expect(result.n).toBe(1)689                expect(result.s1).toBe(base)690            })691        })692693        if (useProxies)694            it("throws when Object.setPrototypeOf() is used on a draft", () => {695                produce({}, draft => {696                    expect(() => Object.setPrototypeOf(draft, Array)).toThrow(697                        "Object.setPrototypeOf() cannot be used on an Immer draft"698                    )699                })700            })701702        it("supports the 'in' operator", () => {703            produce(baseState, draft => {704                // Known property705                expect("anArray" in draft).toBe(true)706                expect(Reflect.has(draft, "anArray")).toBe(true)707708                // Unknown property709                expect("bla" in draft).toBe(false)710                expect(Reflect.has(draft, "bla")).toBe(false)711712                // Known index713                expect(0 in draft.anArray).toBe(true)714                expect("0" in draft.anArray).toBe(true)715                expect(Reflect.has(draft.anArray, 0)).toBe(true)716                expect(Reflect.has(draft.anArray, "0")).toBe(true)717718                // Unknown index719                expect(17 in draft.anArray).toBe(false)720                expect("17" in draft.anArray).toBe(false)721                expect(Reflect.has(draft.anArray, 17)).toBe(false)722                expect(Reflect.has(draft.anArray, "17")).toBe(false)723            })724        })725726        it("'this' should work - 1", () => {727            const base = {x: 3}728            const next1 = produce(base, function() {729                this.x = 4730            })731            expect(next1).not.toBe(base)732            expect(next1.x).toBe(4)733        })734735        it("'this' should work - 2", () => {736            const base = {x: 3}737            const incrementor = produce(function() {738                this.x = 4739            })740            const next1 = incrementor(base)741            expect(next1).not.toBe(base)742            expect(next1.x).toBe(4)743        })744745        // See here: https://github.com/mweststrate/immer/issues/89746        it("supports the spread operator", () => {747            const base = {foo: {x: 0, y: 0}, bar: [0, 0]}748            const result = produce(base, draft => {749                draft.foo = {x: 1, ...draft.foo, y: 1}750                draft.bar = [1, ...draft.bar, 1]751            })752            expect(result).toEqual({753                foo: {x: 0, y: 1},754                bar: [1, 0, 0, 1]755            })756        })757758        it("processes with lodash.set", () => {759            const base = [{id: 1, a: 1}]760            const result = produce(base, draft => {761                lodash.set(draft, "[0].a", 2)762            })763            expect(base[0].a).toEqual(1)764            expect(result[0].a).toEqual(2)765        })766767        it("processes with lodash.find", () => {768            const base = [{id: 1, a: 1}]769            const result = produce(base, draft => {770                const obj1 = lodash.find(draft, {id: 1})771                lodash.set(obj1, "a", 2)772            })773            expect(base[0].a).toEqual(1)774            expect(result[0].a).toEqual(2)775        })776777        describe("recipe functions", () => {778            it("can return a new object", () => {779                const base = {x: 3}780                const res = produce(base, d => {781                    return {x: d.x + 1}782                })783                expect(res).not.toBe(base)784                expect(res).toEqual({x: 4})785            })786787            it("can return the draft", () => {788                const base = {x: 3}789                const res = produce(base, d => {790                    d.x = 4791                    return d792                })793                expect(res).not.toBe(base)794                expect(res).toEqual({x: 4})795            })796797            it("can return a child draft", () => {798                const base = {a: {}}799                const res = produce(base, d => {800                    return d.a801                })802                expect(res).toBe(base.a)803            })804805            it("can return a frozen object", () => {806                const res = deepFreeze([{x: 3}])807                expect(produce({}, () => res)).toBe(res)808            })809810            it("can return an object with two references to another object", () => {811                const next = produce({}, d => {812                    const obj = {}813                    return {obj, arr: [obj]}814                })815                expect(next.obj).toBe(next.arr[0])816            })817818            it("can return an object with two references to any pristine draft", () => {819                const base = {a: {}}820                const next = produce(base, d => {821                    return [d.a, d.a]822                })823                expect(next[0]).toBe(base.a)824                expect(next[0]).toBe(next[1])825            })826827            it("cannot return an object that references itself", () => {828                const res = {}829                res.self = res830                expect(() => {831                    produce(res, () => res.self)832                }).toThrow("Immer forbids circular references")833            })834        })835836        it("throws when the draft is modified and another object is returned", () => {837            const base = {x: 3}838            expect(() => {839                produce(base, draft => {840                    draft.x = 4841                    return {x: 5}842                })843            }).toThrow(/An immer producer returned a new value/)844        })845846        it("should fix #117 - 1", () => {847            const reducer = (state, action) =>848                produce(state, draft => {849                    switch (action.type) {850                        case "SET_STARTING_DOTS":851                            return draft.availableStartingDots.map(a => a)852                        default:853                            break854                    }855                })856            const base = {857                availableStartingDots: [858                    {dots: 4, count: 1},859                    {dots: 3, count: 2},860                    {dots: 2, count: 3},861                    {dots: 1, count: 4}862                ]863            }864            const next = reducer(base, {type: "SET_STARTING_DOTS"})865            expect(next).toEqual(base.availableStartingDots)866            expect(next).not.toBe(base.availableStartingDots)867        })868869        it("should fix #117 - 2", () => {870            const reducer = (state, action) =>871                produce(state, draft => {872                    switch (action.type) {873                        case "SET_STARTING_DOTS":874                            return {875                                dots: draft.availableStartingDots.map(a => a)876                            }877                        default:878                            break879                    }880                })881            const base = {882                availableStartingDots: [883                    {dots: 4, count: 1},884                    {dots: 3, count: 2},885                    {dots: 2, count: 3},886                    {dots: 1, count: 4}887                ]888            }889            const next = reducer(base, {type: "SET_STARTING_DOTS"})890            expect(next).toEqual({dots: base.availableStartingDots})891        })892893        it("cannot always detect noop assignments - 0", () => {894            const baseState = {x: {y: 3}}895            const nextState = produce(baseState, d => {896                const a = d.x897                d.x = a898            })899            expect(nextState).toBe(baseState)900        })901902        it("cannot always detect noop assignments - 1", () => {903            const baseState = {x: {y: 3}}904            const nextState = produce(baseState, d => {905                const a = d.x906                d.x = 4907                d.x = a908            })909            // Ideally, this should actually be the same instances910            // but this would be pretty expensive to detect,911            // so we don't atm912            expect(nextState).not.toBe(baseState)913        })914915        it("cannot always detect noop assignments - 2", () => {916            const baseState = {x: {y: 3}}917            const nextState = produce(baseState, d => {918                const a = d.x919                const stuff = a.y + 3920                d.x = 4921                d.x = a922            })923            // Ideally, this should actually be the same instances924            // but this would be pretty expensive to detect,925            // so we don't atm926            expect(nextState).not.toBe(baseState)927        })928929        it("cannot always detect noop assignments - 3", () => {930            const baseState = {x: 3}931            const nextState = produce(baseState, d => {932                d.x = 3933            })934            expect(nextState).toBe(baseState)935        })936937        it("cannot always detect noop assignments - 4", () => {938            const baseState = {x: 3}939            const nextState = produce(baseState, d => {940                d.x = 4941                d.x = 3942            })943            // Ideally, this should actually be the same instances944            // but this would be pretty expensive to detect,945            // so we don't atm946            expect(nextState).not.toBe(baseState)947        })948949        it("cannot produce undefined by returning undefined", () => {950            const base = 3951            expect(produce(base, () => 4)).toBe(4)952            expect(produce(base, () => null)).toBe(null)953            expect(produce(base, () => undefined)).toBe(3)954            expect(produce(base, () => {})).toBe(3)955            expect(produce(base, () => nothing)).toBe(undefined)956957            expect(produce({}, () => undefined)).toEqual({})958            expect(produce({}, () => nothing)).toBe(undefined)959            expect(produce(3, () => nothing)).toBe(undefined)960961            expect(produce(() => undefined)({})).toEqual({})962            expect(produce(() => nothing)({})).toBe(undefined)963            expect(produce(() => nothing)(3)).toBe(undefined)964        })965966        describe("base state type", () => {967            testObjectTypes(produce)968            testLiteralTypes(produce)969        })970971        afterEach(() => {972            expect(baseState).toBe(origBaseState)973            expect(baseState).toEqual(createBaseState())974        })975976        class Foo {}977        function createBaseState() {978            const data = {979                anInstance: new Foo(),980                anArray: [3, 2, {c: 3}, 1],981                aProp: "hi",982                anObject: {983                    nested: {984                        yummie: true985                    },986                    coffee: false987                }988            }989            return autoFreeze ? deepFreeze(data) : data990        }991    })992993    describe(`isDraft - ${name}`, () => {994        it("returns true for object drafts", () => {995            produce({}, state => {996                expect(isDraft(state)).toBeTruthy()997            })998        })999        it("returns true for array drafts", () => {1000            produce([], state => {1001                expect(isDraft(state)).toBeTruthy()1002            })1003        })1004        it("returns true for objects nested in object drafts", () => {1005            produce({a: {b: {}}}, state => {1006                expect(isDraft(state.a)).toBeTruthy()1007                expect(isDraft(state.a.b)).toBeTruthy()1008            })1009        })1010        it("returns false for new objects added to a draft", () => {1011            produce({}, state => {1012                state.a = {}1013                expect(isDraft(state.a)).toBeFalsy()1014            })1015        })1016        it("returns false for objects returned by the producer", () => {1017            const object = produce(null, Object.create)1018            expect(isDraft(object)).toBeFalsy()1019        })1020        it("returns false for arrays returned by the producer", () => {1021            const array = produce(null, _ => [])1022            expect(isDraft(array)).toBeFalsy()1023        })1024        it("returns false for object drafts returned by the producer", () => {1025            const object = produce({}, state => state)1026            expect(isDraft(object)).toBeFalsy()1027        })1028        it("returns false for array drafts returned by the producer", () => {1029            const array = produce([], state => state)1030            expect(isDraft(array)).toBeFalsy()1031        })1032    })1033}10341035function testObjectTypes(produce) {1036    class Foo {1037        constructor(foo) {1038            this.foo = foo1039            this[immerable] = true1040        }1041    }1042    const values = {1043        "empty object": {},1044        "plain object": {a: 1, b: 2},1045        "object (no prototype)": Object.create(null),1046        "empty array": [],1047        "plain array": [1, 2],1048        "class instance (draftable)": new Foo(1)1049    }1050    for (const name in values) {1051        const value = values[name]1052        const copy = shallowCopy(value)1053        testObjectType(name, value)1054        testObjectType(name + " (frozen)", Object.freeze(copy))1055    }1056    function testObjectType(name, base) {1057        describe(name, () => {1058            it("creates a draft", () => {1059                produce(base, draft => {1060                    expect(draft).not.toBe(base)1061                    expect(shallowCopy(draft, true)).toEqual(base)1062                })1063            })10641065            it("preserves the prototype", () => {1066                const proto = Object.getPrototypeOf(base)1067                produce(base, draft => {1068                    expect(Object.getPrototypeOf(draft)).toBe(proto)1069                })1070            })10711072            it("returns the base state when no changes are made", () => {1073                expect(produce(base, () => {})).toBe(base)1074            })10751076            it("returns a copy when changes are made", () => {1077                const random = Math.random()1078                const result = produce(base, draft => {1079                    draft[0] = random1080                })1081                expect(result).not.toBe(base)1082                expect(result.constructor).toBe(base.constructor)1083                expect(result[0]).toBe(random)1084            })1085        })1086    }1087}10881089function testLiteralTypes(produce) {1090    class Foo {}1091    const values = {1092        "falsy number": 0,1093        "truthy number": 1,1094        "negative number": -1,1095        NaN: NaN,1096        infinity: 1 / 0,1097        true: true,1098        false: false,1099        "empty string": "",1100        "truthy string": "1",1101        null: null,1102        undefined: undefined,11031104        /**1105         * These objects are treated as literals because Immer1106         * does not know how to draft them.1107         */1108        function: () => {},1109        "regexp object": /.+/g,1110        "boxed number": new Number(0),1111        "boxed string": new String(""),1112        "boxed boolean": new Boolean(),1113        "date object": new Date(),1114        "class instance (not draftable)": new Foo()1115    }1116    for (const name in values) {1117        describe(name, () => {1118            const value = values[name]11191120            it("does not create a draft", () => {1121                produce(value, draft => {1122                    expect(draft).toBe(value)1123                })1124            })11251126            it("returns the base state when no changes are made", () => {1127                expect(produce(value, () => {})).toBe(value)1128            })11291130            if (value && typeof value == "object") {1131                it("does not return a copy when changes are made", () => {1132                    expect(1133                        produce(value, draft => {1134                            draft.foo = true1135                        })1136                    ).toBe(value)1137                })1138            }1139        })1140    }1141}11421143function enumerableOnly(x) {1144    const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1145    each(copy, (prop, value) => {1146        if (value && typeof value === "object") {1147            copy[prop] = enumerableOnly(value)1148        }1149    })1150    return copy1151}