Skip to content
Myr

base.js

This file

Path

__tests__/base.js

1,210 lines · 42.6 KiB · JavaScript

Last changed by

test: avoid async/await for node 6aleclarsonbefore adoptione9f274e

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 an unmodified 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        // TODO: rewrite tests with async/await once node 6 support is dropped837        describe("async recipe function", () => {838            it("can modify the draft", () => {839                const base = {a: 0, b: 0}840                return produce(base, d => {841                    d.a = 1842                    return Promise.resolve().then(() => {843                        d.b = 1844                    })845                }).then(res => {846                    expect(res).not.toBe(base)847                    expect(res).toEqual({a: 1, b: 1})848                })849            })850851            it("works with rejected promises", () => {852                let draft853                const base = {a: 0, b: 0}854                const err = new Error("passed")855                return produce(base, d => {856                    draft = d857                    draft.b = 1858                    return Promise.reject(err)859                }).then(860                    () => {861                        throw "failed"862                    },863                    e => {864                        expect(e).toBe(err)865                        expect(() => draft.a).toThrowError(/revoked/)866                    }867                )868            })869870            it("supports recursive produce calls after await", () => {871                const base = {obj: {k: 1}}872                return produce(base, d => {873                    const obj = d.obj874                    delete d.obj875                    return Promise.resolve().then(() => {876                        d.a = produce({}, d => {877                            d.b = obj // Assign a draft owned by the parent scope.878                        })879880                        // Auto-freezing is prevented when an unowned draft exists.881                        expect(Object.isFrozen(d.a)).toBeFalsy()882883                        // Ensure `obj` is not revoked.884                        obj.c = 1885                    })886                }).then(res => {887                    expect(res).not.toBe(base)888                    expect(res).toEqual({889                        a: {b: {k: 1, c: 1}}890                    })891                })892            })893        })894895        it("throws when the draft is modified and another object is returned", () => {896            const base = {x: 3}897            expect(() => {898                produce(base, draft => {899                    draft.x = 4900                    return {x: 5}901                })902            }).toThrow(/An immer producer returned a new value/)903        })904905        it("should fix #117 - 1", () => {906            const reducer = (state, action) =>907                produce(state, draft => {908                    switch (action.type) {909                        case "SET_STARTING_DOTS":910                            return draft.availableStartingDots.map(a => a)911                        default:912                            break913                    }914                })915            const base = {916                availableStartingDots: [917                    {dots: 4, count: 1},918                    {dots: 3, count: 2},919                    {dots: 2, count: 3},920                    {dots: 1, count: 4}921                ]922            }923            const next = reducer(base, {type: "SET_STARTING_DOTS"})924            expect(next).toEqual(base.availableStartingDots)925            expect(next).not.toBe(base.availableStartingDots)926        })927928        it("should fix #117 - 2", () => {929            const reducer = (state, action) =>930                produce(state, draft => {931                    switch (action.type) {932                        case "SET_STARTING_DOTS":933                            return {934                                dots: draft.availableStartingDots.map(a => a)935                            }936                        default:937                            break938                    }939                })940            const base = {941                availableStartingDots: [942                    {dots: 4, count: 1},943                    {dots: 3, count: 2},944                    {dots: 2, count: 3},945                    {dots: 1, count: 4}946                ]947            }948            const next = reducer(base, {type: "SET_STARTING_DOTS"})949            expect(next).toEqual({dots: base.availableStartingDots})950        })951952        it("cannot always detect noop assignments - 0", () => {953            const baseState = {x: {y: 3}}954            const nextState = produce(baseState, d => {955                const a = d.x956                d.x = a957            })958            expect(nextState).toBe(baseState)959        })960961        it("cannot always detect noop assignments - 1", () => {962            const baseState = {x: {y: 3}}963            const nextState = produce(baseState, d => {964                const a = d.x965                d.x = 4966                d.x = a967            })968            // Ideally, this should actually be the same instances969            // but this would be pretty expensive to detect,970            // so we don't atm971            expect(nextState).not.toBe(baseState)972        })973974        it("cannot always detect noop assignments - 2", () => {975            const baseState = {x: {y: 3}}976            const nextState = produce(baseState, d => {977                const a = d.x978                const stuff = a.y + 3979                d.x = 4980                d.x = a981            })982            // Ideally, this should actually be the same instances983            // but this would be pretty expensive to detect,984            // so we don't atm985            expect(nextState).not.toBe(baseState)986        })987988        it("cannot always detect noop assignments - 3", () => {989            const baseState = {x: 3}990            const nextState = produce(baseState, d => {991                d.x = 3992            })993            expect(nextState).toBe(baseState)994        })995996        it("cannot always detect noop assignments - 4", () => {997            const baseState = {x: 3}998            const nextState = produce(baseState, d => {999                d.x = 41000                d.x = 31001            })1002            // Ideally, this should actually be the same instances1003            // but this would be pretty expensive to detect,1004            // so we don't atm1005            expect(nextState).not.toBe(baseState)1006        })10071008        it("cannot produce undefined by returning undefined", () => {1009            const base = 31010            expect(produce(base, () => 4)).toBe(4)1011            expect(produce(base, () => null)).toBe(null)1012            expect(produce(base, () => undefined)).toBe(3)1013            expect(produce(base, () => {})).toBe(3)1014            expect(produce(base, () => nothing)).toBe(undefined)10151016            expect(produce({}, () => undefined)).toEqual({})1017            expect(produce({}, () => nothing)).toBe(undefined)1018            expect(produce(3, () => nothing)).toBe(undefined)10191020            expect(produce(() => undefined)({})).toEqual({})1021            expect(produce(() => nothing)({})).toBe(undefined)1022            expect(produce(() => nothing)(3)).toBe(undefined)1023        })10241025        describe("base state type", () => {1026            testObjectTypes(produce)1027            testLiteralTypes(produce)1028        })10291030        afterEach(() => {1031            expect(baseState).toBe(origBaseState)1032            expect(baseState).toEqual(createBaseState())1033        })10341035        class Foo {}1036        function createBaseState() {1037            const data = {1038                anInstance: new Foo(),1039                anArray: [3, 2, {c: 3}, 1],1040                aProp: "hi",1041                anObject: {1042                    nested: {1043                        yummie: true1044                    },1045                    coffee: false1046                }1047            }1048            return autoFreeze ? deepFreeze(data) : data1049        }1050    })10511052    describe(`isDraft - ${name}`, () => {1053        it("returns true for object drafts", () => {1054            produce({}, state => {1055                expect(isDraft(state)).toBeTruthy()1056            })1057        })1058        it("returns true for array drafts", () => {1059            produce([], state => {1060                expect(isDraft(state)).toBeTruthy()1061            })1062        })1063        it("returns true for objects nested in object drafts", () => {1064            produce({a: {b: {}}}, state => {1065                expect(isDraft(state.a)).toBeTruthy()1066                expect(isDraft(state.a.b)).toBeTruthy()1067            })1068        })1069        it("returns false for new objects added to a draft", () => {1070            produce({}, state => {1071                state.a = {}1072                expect(isDraft(state.a)).toBeFalsy()1073            })1074        })1075        it("returns false for objects returned by the producer", () => {1076            const object = produce(null, Object.create)1077            expect(isDraft(object)).toBeFalsy()1078        })1079        it("returns false for arrays returned by the producer", () => {1080            const array = produce(null, _ => [])1081            expect(isDraft(array)).toBeFalsy()1082        })1083        it("returns false for object drafts returned by the producer", () => {1084            const object = produce({}, state => state)1085            expect(isDraft(object)).toBeFalsy()1086        })1087        it("returns false for array drafts returned by the producer", () => {1088            const array = produce([], state => state)1089            expect(isDraft(array)).toBeFalsy()1090        })1091    })1092}10931094function testObjectTypes(produce) {1095    class Foo {1096        constructor(foo) {1097            this.foo = foo1098            this[immerable] = true1099        }1100    }1101    const values = {1102        "empty object": {},1103        "plain object": {a: 1, b: 2},1104        "object (no prototype)": Object.create(null),1105        "empty array": [],1106        "plain array": [1, 2],1107        "class instance (draftable)": new Foo(1)1108    }1109    for (const name in values) {1110        const value = values[name]1111        const copy = shallowCopy(value)1112        testObjectType(name, value)1113        testObjectType(name + " (frozen)", Object.freeze(copy))1114    }1115    function testObjectType(name, base) {1116        describe(name, () => {1117            it("creates a draft", () => {1118                produce(base, draft => {1119                    expect(draft).not.toBe(base)1120                    expect(shallowCopy(draft, true)).toEqual(base)1121                })1122            })11231124            it("preserves the prototype", () => {1125                const proto = Object.getPrototypeOf(base)1126                produce(base, draft => {1127                    expect(Object.getPrototypeOf(draft)).toBe(proto)1128                })1129            })11301131            it("returns the base state when no changes are made", () => {1132                expect(produce(base, () => {})).toBe(base)1133            })11341135            it("returns a copy when changes are made", () => {1136                const random = Math.random()1137                const result = produce(base, draft => {1138                    draft[0] = random1139                })1140                expect(result).not.toBe(base)1141                expect(result.constructor).toBe(base.constructor)1142                expect(result[0]).toBe(random)1143            })1144        })1145    }1146}11471148function testLiteralTypes(produce) {1149    class Foo {}1150    const values = {1151        "falsy number": 0,1152        "truthy number": 1,1153        "negative number": -1,1154        NaN: NaN,1155        infinity: 1 / 0,1156        true: true,1157        false: false,1158        "empty string": "",1159        "truthy string": "1",1160        null: null,1161        undefined: undefined,11621163        /**1164         * These objects are treated as literals because Immer1165         * does not know how to draft them.1166         */1167        function: () => {},1168        "regexp object": /.+/g,1169        "boxed number": new Number(0),1170        "boxed string": new String(""),1171        "boxed boolean": new Boolean(),1172        "date object": new Date(),1173        "class instance (not draftable)": new Foo()1174    }1175    for (const name in values) {1176        describe(name, () => {1177            const value = values[name]11781179            it("does not create a draft", () => {1180                produce(value, draft => {1181                    expect(draft).toBe(value)1182                })1183            })11841185            it("returns the base state when no changes are made", () => {1186                expect(produce(value, () => {})).toBe(value)1187            })11881189            if (value && typeof value == "object") {1190                it("does not return a copy when changes are made", () => {1191                    expect(1192                        produce(value, draft => {1193                            draft.foo = true1194                        })1195                    ).toBe(value)1196                })1197            }1198        })1199    }1200}12011202function enumerableOnly(x) {1203    const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1204    each(copy, (prop, value) => {1205        if (value && typeof value === "object") {1206            copy[prop] = enumerableOnly(value)1207        }1208    })1209    return copy1210}