Skip to content
Myr

base.js

This file

Path

__tests__/base.js

1,731 lines · 64.6 KiB · JavaScript

Last changed by

feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5

History of this file

Take it

1"use strict"2import {Immer, nothing, original, isDraft, immerable} from "../src/index"3import {each, shallowCopy, isEnumerable, DRAFT_STATE} 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        if (useProxies) {303            describe("map drafts", () => {304                it("supports key access", () => {305                    const value = baseState.aMap.get("jedi")306                    const nextState = produce(baseState, s => {307                        expect(s.aMap.get("jedi")).toEqual(value)308                    })309                    expect(nextState).toBe(baseState)310                })311312                it("supports key access for non-primitive keys", () => {313                    const key = {prop: "val"}314                    const base = new Map([[key, {id: 1, a: 1}]])315                    const value = base.get(key)316                    const nextState = produce(base, s => {317                        expect(s.get(key)).toEqual(value)318                    })319                    expect(nextState).toBe(base)320                })321322                it("supports iteration", () => {323                    const base = new Map([324                        ["first", {id: 1, a: 1}],325                        ["second", {id: 2, a: 1}]326                    ])327                    const findById = (map, id) => {328                        for (const [, item] of map) {329                            if (item.id === id) return item330                        }331                        return null332                    }333                    const result = produce(base, draft => {334                        const obj1 = findById(draft, 1)335                        const obj2 = findById(draft, 2)336                        obj1.a = 2337                        obj2.a = 2338                    })339                    expect(result).not.toBe(base)340                    expect(result.get("first").a).toEqual(2)341                    expect(result.get("second").a).toEqual(2)342                })343344                it("supports 'entries'", () => {345                    const base = new Map([346                        ["first", {id: 1, a: 1}],347                        ["second", {id: 2, a: 1}]348                    ])349                    const findById = (map, id) => {350                        for (const [, item] of map.entries()) {351                            if (item.id === id) return item352                        }353                        return null354                    }355                    const result = produce(base, draft => {356                        const obj1 = findById(draft, 1)357                        const obj2 = findById(draft, 2)358                        obj1.a = 2359                        obj2.a = 2360                    })361                    expect(result).not.toBe(base)362                    expect(result.get("first").a).toEqual(2)363                    expect(result.get("second").a).toEqual(2)364                })365366                it("supports 'values'", () => {367                    const base = new Map([368                        ["first", {id: 1, a: 1}],369                        ["second", {id: 2, a: 1}]370                    ])371                    const findById = (map, id) => {372                        for (const item of map.values()) {373                            if (item.id === id) return item374                        }375                        return null376                    }377                    const result = produce(base, draft => {378                        const obj1 = findById(draft, 1)379                        const obj2 = findById(draft, 2)380                        obj1.a = 2381                        obj2.a = 2382                    })383                    expect(result).not.toBe(base)384                    expect(result.get("first").a).toEqual(2)385                    expect(result.get("second").a).toEqual(2)386                })387388                it("supports 'keys", () => {389                    const base = new Map([390                        ["first", Symbol()],391                        ["second", Symbol()]392                    ])393                    const result = produce(base, draft => {394                        expect([...draft.keys()]).toEqual(["first", "second"])395                        draft.set("third", Symbol())396                        expect([...draft.keys()]).toEqual([397                            "first",398                            "second",399                            "third"400                        ])401                    })402                })403404                it("supports forEach", () => {405                    const key1 = {prop: "val1"}406                    const key2 = {prop: "val2"}407                    const base = new Map([408                        ["first", {id: 1, a: 1}],409                        ["second", {id: 2, a: 1}],410                        [key1, {id: 3, a: 1}],411                        [key2, {id: 4, a: 1}]412                    ])413                    const result = produce(base, draft => {414                        let sum1 = 0415                        draft.forEach(({a}) => {416                            sum1 += a417                        })418                        expect(sum1).toBe(4)419                        let sum2 = 0420                        draft.get("first").a = 10421                        draft.get("second").a = 20422                        draft.get(key1).a = 30423                        draft.get(key2).a = 40424                        draft.forEach(({a}) => {425                            sum2 += a426                        })427                        expect(sum2).toBe(100)428                    })429                    expect(result).not.toBe(base)430                    expect(base.get("first").a).toEqual(1)431                    expect(base.get("second").a).toEqual(1)432                    expect(base.get(key1).a).toEqual(1)433                    expect(base.get(key2).a).toEqual(1)434                    expect(result.get("first").a).toEqual(10)435                    expect(result.get("second").a).toEqual(20)436                    expect(result.get(key1).a).toEqual(30)437                    expect(result.get(key2).a).toEqual(40)438                })439440                it("supports forEach mutation", () => {441                    const base = new Map([442                        ["first", {id: 1, a: 1}],443                        ["second", {id: 2, a: 1}]444                    ])445                    const result = produce(base, draft => {446                        draft.forEach(item => {447                            item.a = 100448                        })449                    })450                    expect(result).not.toBe(base)451                    expect(result.get("first").a).toEqual(100)452                    expect(result.get("second").a).toEqual(100)453                })454455                it("can assign by key", () => {456                    const nextState = produce(baseState, s => {457                        // Map.prototype.set should return the Map itself458                        const res = s.aMap.set("force", true)459                        expect(res).toBe(s.aMap[DRAFT_STATE].draft)460                    })461                    expect(nextState).not.toBe(baseState)462                    expect(nextState.aMap).not.toBe(baseState.aMap)463                    expect(nextState.aMap.get("force")).toEqual(true)464                })465466                it("can assign by a non-primitive key", () => {467                    const key = {prop: "val"}468                    const value = {id: 1, a: 1}469                    const base = new Map([[key, value]])470                    const nextState = produce(base, s => {471                        s.set(key, true)472                    })473                    expect(nextState).not.toBe(base)474                    expect(base.get(key)).toEqual(value)475                    expect(nextState.get(key)).toEqual(true)476                })477478                it("state stays the same if the the same item is assigned by key", () => {479                    const nextState = produce(baseState, s => {480                        s.aMap.set("jediTotal", 42)481                    })482                    expect(nextState).toBe(baseState)483                    expect(nextState.aMap).toBe(baseState.aMap)484                })485486                it("returns 'size'", () => {487                    const nextState = produce(baseState, s => {488                        s.aMap.set("newKey", true)489                        expect(s.aMap.size).toBe(baseState.aMap.size + 1)490                    })491                    expect(nextState).not.toBe(baseState)492                    expect(nextState.aMap).not.toBe(baseState.aMap)493                    expect(nextState.aMap.get("newKey")).toEqual(true)494                    expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)495                })496497                it("can use 'delete' to remove items", () => {498                    const nextState = produce(baseState, s => {499                        expect(s.aMap.has("jedi")).toBe(true)500                        s.aMap.delete("jedi")501                        expect(s.aMap.has("jedi")).toBe(false)502                    })503                    expect(nextState.aMap).not.toBe(baseState.aMap)504                    expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)505                    expect(baseState.aMap.has("jedi")).toBe(true)506                    expect(nextState.aMap.has("jedi")).toBe(false)507                })508509                it("can use 'clear' to remove items", () => {510                    const nextState = produce(baseState, s => {511                        expect(s.aMap.size).not.toBe(0)512                        s.aMap.clear()513                        expect(s.aMap.size).toBe(0)514                    })515                    expect(nextState.aMap).not.toBe(baseState.aMap)516                    expect(baseState.aMap.size).not.toBe(0)517                    expect(nextState.aMap.size).toBe(0)518                })519520                it("support 'has'", () => {521                    const nextState = produce(baseState, s => {522                        expect(s.aMap.has("newKey")).toBe(false)523                        s.aMap.set("newKey", true)524                        expect(s.aMap.has("newKey")).toBe(true)525                    })526                    expect(nextState).not.toBe(baseState)527                    expect(nextState.aMap).not.toBe(baseState.aMap)528                    expect(baseState.aMap.has("newKey")).toBe(false)529                    expect(nextState.aMap.has("newKey")).toBe(true)530                })531532                it("supports nested maps", () => {533                    const base = new Map([534                        ["first", new Map([["second", {prop: "test"}]])]535                    ])536                    const result = produce(base, draft => {537                        draft.get("first").get("second").prop = "test1"538                    })539                    expect(result).not.toBe(base)540                    expect(result.get("first")).not.toBe(base.get("first"))541                    expect(result.get("first").get("second")).not.toBe(542                        base.get("first").get("second")543                    )544                    expect(base.get("first").get("second").prop).toBe("test")545                    expect(result.get("first").get("second").prop).toBe("test1")546                })547            })548549            describe("set drafts", () => {550                it("supports iteration", () => {551                    const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])552                    const findById = (set, id) => {553                        for (const item of set) {554                            if (item.id === id) return item555                        }556                        return null557                    }558                    const result = produce(base, draft => {559                        const obj1 = findById(draft, 1)560                        const obj2 = findById(draft, 2)561                        obj1.a = 2562                        obj2.a = 2563                    })564                    expect(result).not.toBe(base)565                    expect(base).toEqual(566                        new Set([{id: 1, a: 1}, {id: 2, a: 1}])567                    )568                    expect(result).toEqual(569                        new Set([{id: 1, a: 2}, {id: 2, a: 2}])570                    )571                })572573                it("supports 'entries'", () => {574                    const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])575                    const findById = (set, id) => {576                        for (const [item1, item2] of set.entries()) {577                            expect(item1).toBe(item2)578                            if (item1.id === id) return item1579                        }580                        return null581                    }582                    const result = produce(base, draft => {583                        const obj1 = findById(draft, 1)584                        const obj2 = findById(draft, 2)585                        obj1.a = 2586                        obj2.a = 2587                    })588                    expect(result).not.toBe(base)589                    expect(base).toEqual(590                        new Set([{id: 1, a: 1}, {id: 2, a: 1}])591                    )592                    expect(result).toEqual(593                        new Set([{id: 1, a: 2}, {id: 2, a: 2}])594                    )595                })596597                it("supports 'values'", () => {598                    const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])599                    const findById = (set, id) => {600                        for (const item of set.values()) {601                            if (item.id === id) return item602                        }603                        return null604                    }605                    const result = produce(base, draft => {606                        const obj1 = findById(draft, 1)607                        const obj2 = findById(draft, 2)608                        obj1.a = 2609                        obj2.a = 2610                    })611                    expect(result).not.toBe(base)612                    expect(base).toEqual(613                        new Set([{id: 1, a: 1}, {id: 2, a: 1}])614                    )615                    expect(result).toEqual(616                        new Set([{id: 1, a: 2}, {id: 2, a: 2}])617                    )618                })619620                it("supports 'keys'", () => {621                    const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])622                    const findById = (set, id) => {623                        for (const item of set.keys()) {624                            if (item.id === id) return item625                        }626                        return null627                    }628                    const result = produce(base, draft => {629                        const obj1 = findById(draft, 1)630                        const obj2 = findById(draft, 2)631                        obj1.a = 2632                        obj2.a = 2633                    })634                    expect(result).not.toBe(base)635                    expect(base).toEqual(636                        new Set([{id: 1, a: 1}, {id: 2, a: 1}])637                    )638                    expect(result).toEqual(639                        new Set([{id: 1, a: 2}, {id: 2, a: 2}])640                    )641                })642643                it("supports forEach with mutation after reads", () => {644                    const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])645                    const result = produce(base, draft => {646                        let sum1 = 0647                        draft.forEach(({a}) => {648                            sum1 += a649                        })650                        expect(sum1).toBe(3)651                        let sum2 = 0652                        draft.forEach(item => {653                            item.a += 10654                            sum2 += item.a655                        })656                        expect(sum2).toBe(23)657                    })658                    expect(result).not.toBe(base)659                    expect(base).toEqual(660                        new Set([{id: 1, a: 1}, {id: 2, a: 2}])661                    )662                    expect(result).toEqual(663                        new Set([{id: 1, a: 11}, {id: 2, a: 12}])664                    )665                })666667                it("state stays the same if the same item is added", () => {668                    const nextState = produce(baseState, s => {669                        s.aSet.add("Luke")670                    })671                    expect(nextState).toBe(baseState)672                    expect(nextState.aSet).toBe(baseState.aSet)673                })674675                it("can add new items", () => {676                    const nextState = produce(baseState, s => {677                        // Set.prototype.set should return the Set itself678                        const res = s.aSet.add("force")679                        expect(res).toBe(s.aSet[DRAFT_STATE].draft)680                    })681                    expect(nextState).not.toBe(baseState)682                    expect(nextState.aSet).not.toBe(baseState.aSet)683                    expect(baseState.aSet.has("force")).toBe(false)684                    expect(nextState.aSet.has("force")).toBe(true)685                })686687                it("returns 'size'", () => {688                    const nextState = produce(baseState, s => {689                        s.aSet.add("newKey")690                        expect(s.aSet.size).toBe(baseState.aSet.size + 1)691                    })692                    expect(nextState).not.toBe(baseState)693                    expect(nextState.aSet).not.toBe(baseState.aSet)694                    expect(nextState.aSet.has("newKey")).toBe(true)695                    expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)696                })697698                it("can use 'delete' to remove items", () => {699                    const nextState = produce(baseState, s => {700                        expect(s.aSet.has("Luke")).toBe(true)701                        s.aSet.delete("Luke")702                        expect(s.aSet.has("Luke")).toBe(false)703                    })704                    expect(nextState.aSet).not.toBe(baseState.aSet)705                    expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)706                    expect(baseState.aSet.has("Luke")).toBe(true)707                    expect(nextState.aSet.has("Luke")).toBe(false)708                })709710                it("can use 'clear' to remove items", () => {711                    const nextState = produce(baseState, s => {712                        expect(s.aSet.size).not.toBe(0)713                        s.aSet.clear()714                        expect(s.aSet.size).toBe(0)715                    })716                    expect(nextState.aSet).not.toBe(baseState.aSet)717                    expect(baseState.aSet.size).not.toBe(0)718                    expect(nextState.aSet.size).toBe(0)719                })720721                it("supports 'has'", () => {722                    const nextState = produce(baseState, s => {723                        expect(s.aSet.has("newKey")).toBe(false)724                        s.aSet.add("newKey")725                        expect(s.aSet.has("newKey")).toBe(true)726                    })727                    expect(nextState).not.toBe(baseState)728                    expect(nextState.aSet).not.toBe(baseState.aSet)729                    expect(baseState.aSet.has("newKey")).toBe(false)730                    expect(nextState.aSet.has("newKey")).toBe(true)731                })732733                it("supports nested sets", () => {734                    const base = new Set([new Set(["Serenity"])])735                    const result = produce(base, draft => {736                        draft.forEach(nestedItem => nestedItem.add("Firefly"))737                    })738                    expect(result).not.toBe(base)739                    expect(base).toEqual(new Set([new Set(["Serenity"])]))740                    expect(result).toEqual(741                        new Set([new Set(["Serenity", "Firefly"])])742                    )743                })744            })745        }746747        it("supports `immerable` symbol on constructor", () => {748            class One {}749            One[immerable] = true750            const baseState = new One()751            const nextState = produce(baseState, draft => {752                expect(draft).not.toBe(baseState)753                draft.foo = true754            })755            expect(nextState).not.toBe(baseState)756            expect(nextState.foo).toBeTruthy()757        })758759        it("preserves symbol properties", () => {760            const test = Symbol("test")761            const baseState = {[test]: true}762            const nextState = produce(baseState, s => {763                expect(s[test]).toBeTruthy()764                s.foo = true765            })766            expect(nextState).toEqual({767                [test]: true,768                foo: true769            })770        })771772        it("preserves non-enumerable properties", () => {773            const baseState = {}774            // Non-enumerable object property775            Object.defineProperty(baseState, "foo", {776                value: {a: 1},777                enumerable: false778            })779            // Non-enumerable primitive property780            Object.defineProperty(baseState, "bar", {781                value: 1,782                enumerable: false783            })784            const nextState = produce(baseState, s => {785                expect(s.foo).toBeTruthy()786                expect(isEnumerable(s, "foo")).toBeFalsy()787                s.bar++788                expect(isEnumerable(s, "foo")).toBeFalsy()789                s.foo.a++790                expect(isEnumerable(s, "foo")).toBeFalsy()791            })792            expect(nextState.foo).toBeTruthy()793            expect(isEnumerable(nextState, "foo")).toBeFalsy()794        })795796        it("throws on computed properties", () => {797            const baseState = {}798            Object.defineProperty(baseState, "foo", {799                get: () => {},800                enumerable: true801            })802            expect(() => {803                produce(baseState, s => {804                    // Proxies only throw once a change is made.805                    if (useProxies) {806                        s.modified = true807                    }808                })809            }).toThrowErrorMatchingSnapshot()810        })811812        it("allows inherited computed properties", () => {813            const proto = {}814            Object.defineProperty(proto, "foo", {815                get() {816                    return this.bar817                },818                set(val) {819                    this.bar = val820                }821            })822            const baseState = Object.create(proto)823            produce(baseState, s => {824                expect(s.bar).toBeUndefined()825                s.foo = {}826                expect(s.bar).toBeDefined()827                expect(s.foo).toBe(s.bar)828            })829        })830831        it("supports a base state with multiple references to an object", () => {832            const obj = {}833            const res = produce({a: obj, b: obj}, d => {834                // Two drafts are created for each occurrence of an object in the base state.835                expect(d.a).not.toBe(d.b)836                d.a.z = true837                expect(d.b.z).toBeUndefined()838            })839            expect(res.b).toBe(obj)840            expect(res.a).not.toBe(res.b)841            expect(res.a.z).toBeTruthy()842        })843844        // NOTE: Except the root draft.845        it("supports multiple references to any modified draft", () => {846            const next = produce({a: {b: 1}}, d => {847                d.a.b++848                d.b = d.a849            })850            expect(next.a).toBe(next.b)851        })852853        it("can rename nested objects (no changes)", () => {854            const nextState = produce({obj: {}}, s => {855                s.foo = s.obj856                delete s.obj857            })858            expect(nextState).toEqual({foo: {}})859        })860861        // Very similar to the test before, but the reused object has one862        // property changed, one added, and one removed.863        it("can rename nested objects (with changes)", () => {864            const nextState = produce({obj: {a: 1, b: 1}}, s => {865                s.obj.a = true // change866                delete s.obj.b // delete867                s.obj.c = true // add868869                s.foo = s.obj870                delete s.obj871            })872            expect(nextState).toEqual({foo: {a: true, c: true}})873        })874875        it("can nest a draft in a new object (no changes)", () => {876            const baseState = {obj: {}}877            const nextState = produce(baseState, s => {878                s.foo = {bar: s.obj}879                delete s.obj880            })881            expect(nextState.foo.bar).toBe(baseState.obj)882        })883884        it("can nest a modified draft in a new object", () => {885            const nextState = produce({obj: {a: 1, b: 1}}, s => {886                s.obj.a = true // change887                delete s.obj.b // delete888                s.obj.c = true // add889890                s.foo = {bar: s.obj}891                delete s.obj892            })893            expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})894        })895896        it("supports assigning undefined to an existing property", () => {897            const nextState = produce(baseState, s => {898                s.aProp = undefined899            })900            expect(nextState).not.toBe(baseState)901            expect(nextState.aProp).toBe(undefined)902        })903904        it("supports assigning undefined to a new property", () => {905            const baseState = {}906            const nextState = produce(baseState, s => {907                s.aProp = undefined908            })909            expect(nextState).not.toBe(baseState)910            expect(nextState.aProp).toBe(undefined)911        })912913        // NOTE: ES5 drafts only protect existing properties when revoked.914        it("revokes the draft once produce returns", () => {915            const expectRevoked = (fn, shouldThrow = true) => {916                if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()917                else expect(fn).not.toThrow()918            }919920            // Test object drafts:921            let draft922            produce({a: 1, b: 1}, s => {923                draft = s924                delete s.b925            })926927            // Access known property on object draft.928            expectRevoked(() => {929                draft.a930            })931932            // Assign known property on object draft.933            expectRevoked(() => {934                draft.a = true935            })936937            // Access unknown property on object draft.938            expectRevoked(() => {939                draft.z940            }, useProxies)941942            // Assign unknown property on object draft.943            expectRevoked(() => {944                draft.z = true945            }, useProxies)946947            // Test array drafts:948            produce([1, 2], s => {949                draft = s950                s.pop()951            })952953            // Access known index of an array draft.954            expectRevoked(() => {955                draft[0]956            })957958            // Assign known index of an array draft.959            expectRevoked(() => {960                draft[0] = true961            })962963            // Access unknown index of an array draft.964            expectRevoked(() => {965                draft[1]966            }, useProxies)967968            // Assign unknown index of an array draft.969            expectRevoked(() => {970                draft[1] = true971            }, useProxies)972        })973974        it("can access a child draft that was created before the draft was modified", () => {975            produce({a: {}}, s => {976                const before = s.a977                s.b = 1978                expect(s.a).toBe(before)979            })980        })981982        it("should reflect all changes made in the draft immediately", () => {983            produce(baseState, draft => {984                draft.anArray[0] = 5985                draft.anArray.unshift("test")986                expect(enumerableOnly(draft.anArray)).toEqual([987                    "test",988                    5,989                    2,990                    {c: 3},991                    1992                ])993                draft.stuffz = "coffee"994                expect(draft.stuffz).toBe("coffee")995            })996        })997998        if (useProxies)999            it("throws when Object.defineProperty() is used on drafts", () => {1000                expect(() => {1001                    produce({}, draft => {1002                        Object.defineProperty(draft, "xx", {1003                            enumerable: true,1004                            writeable: true,1005                            value: 21006                        })1007                    })1008                }).toThrowErrorMatchingSnapshot()1009            })10101011        it("should handle constructor correctly", () => {1012            const baseState = {1013                arr: new Array(),1014                obj: new Object()1015            }1016            const result = produce(baseState, draft => {1017                draft.arrConstructed = draft.arr.constructor(1)1018                draft.objConstructed = draft.obj.constructor(1)1019            })1020            expect(result.arrConstructed).toEqual(new Array().constructor(1))1021            expect(result.objConstructed).toEqual(new Object().constructor(1))1022        })10231024        it("should handle equality correctly - 1", () => {1025            const baseState = {1026                y: 3 / 0,1027                z: NaN1028            }1029            const nextState = produce(baseState, draft => {1030                draft.y = 4 / 01031                draft.z = NaN1032            })1033            expect(nextState).toBe(baseState)1034        })10351036        it("should handle equality correctly - 2", () => {1037            const baseState = {1038                x: -01039            }1040            const nextState = produce(baseState, draft => {1041                draft.x = +01042            })1043            expect(nextState).not.toBe(baseState)1044            expect(nextState).not.toEqual(baseState)1045        })10461047        // AKA: recursive produce calls1048        describe("nested producers", () => {1049            describe("when base state is not a draft", () => {1050                // This test ensures the global state used to manage proxies is1051                // never left in a corrupted state by a nested `produce` call.1052                it("never affects its parent producer implicitly", () => {1053                    const base = {obj: {a: 1}}1054                    const next = produce(base, draft => {1055                        // Notice how `base.obj` is passed, not `draft.obj`1056                        const obj2 = produce(base.obj, draft2 => {1057                            draft2.a = 01058                        })1059                        expect(obj2.a).toBe(0)1060                        expect(draft.obj.a).toBe(1) // effects should not be visible outside1061                    })1062                    expect(next).toBe(base)1063                })1064            })10651066            describe("when base state is a draft", () => {1067                it("always wraps the draft in a new draft", () => {1068                    produce({}, parent => {1069                        produce(parent, child => {1070                            expect(child).not.toBe(parent)1071                            expect(isDraft(child)).toBeTruthy()1072                            expect(original(child)).toBe(parent)1073                        })1074                    })1075                })10761077                // Reported by: https://github.com/mweststrate/immer/issues/3431078                it("ensures each property is drafted", () => {1079                    produce({a: {}, b: {}}, parent => {1080                        parent.a // Access "a" but not "b"1081                        produce(parent, child => {1082                            child.c = 11083                            expect(isDraft(child.a)).toBeTruthy()1084                            expect(isDraft(child.b)).toBeTruthy()1085                        })1086                    })1087                })10881089                it("preserves any pending changes", () => {1090                    produce({a: 1, b: 1, d: 1}, parent => {1091                        parent.b = 21092                        parent.c = 21093                        delete parent.d1094                        produce(parent, child => {1095                            expect(child.a).toBe(1) // unchanged1096                            expect(child.b).toBe(2) // changed1097                            expect(child.c).toBe(2) // added1098                            expect(child.d).toBeUndefined() // deleted1099                        })1100                    })1101                })1102            })11031104            describe("when base state contains a draft", () => {1105                it("wraps unowned draft with its own draft", () => {1106                    produce({a: {}}, parent => {1107                        produce({a: parent.a}, child => {1108                            expect(child.a).not.toBe(parent.a)1109                            expect(isDraft(child.a)).toBeTruthy()1110                            expect(original(child.a)).toBe(parent.a)1111                        })1112                    })1113                })11141115                it("returns unowned draft if no changes were made", () => {1116                    produce({a: {}}, parent => {1117                        const result = produce({a: parent.a}, () => {})1118                        expect(result.a).toBe(parent.a)1119                    })1120                })11211122                it("clones the unowned draft when changes are made", () => {1123                    produce({a: {}}, parent => {1124                        const result = produce({a: parent.a}, child => {1125                            child.a.b = 11126                        })1127                        expect(result.a).not.toBe(parent.a)1128                        expect(result.a.b).toBe(1)1129                        expect("b" in parent.a).toBeFalsy()1130                    })1131                })11321133                // We cannot auto-freeze the result of a nested producer,1134                // because it may contain a draft from a parent producer.1135                it("never auto-freezes the result", () => {1136                    produce({a: {}}, parent => {1137                        const r = produce({a: parent.a}, child => {1138                            child.b = 1 // Ensure a copy is returned.1139                        })1140                        expect(Object.isFrozen(r)).toBeFalsy()1141                    })1142                })1143            })11441145            // "Upvalues" are variables from a parent scope.1146            it("does not finalize upvalue drafts", () => {1147                produce({a: {}, b: {}}, parent => {1148                    expect(produce({}, () => parent)).toBe(parent)1149                    parent.x // Ensure proxy not revoked.11501151                    expect(produce({}, () => [parent])[0]).toBe(parent)1152                    parent.x // Ensure proxy not revoked.11531154                    expect(produce({}, () => parent.a)).toBe(parent.a)1155                    parent.a.x // Ensure proxy not revoked.11561157                    // Modified parent test1158                    parent.c = 11159                    expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1160                    parent.b.x // Ensure proxy not revoked.1161                })1162            })11631164            it("works with interweaved Immer instances", () => {1165                const options = {useProxies, autoFreeze}1166                const one = createPatchedImmer(options)1167                const two = createPatchedImmer(options)11681169                const base = {}1170                const result = one.produce(base, s1 =>1171                    two.produce({s1}, s2 => {1172                        expect(original(s2.s1)).toBe(s1)1173                        s2.n = 11174                        s2.s1 = one.produce({s2}, s3 => {1175                            expect(original(s3.s2)).toBe(s2)1176                            expect(original(s3.s2.s1)).toBe(s2.s1)1177                            return s3.s2.s11178                        })1179                    })1180                )1181                expect(result.n).toBe(1)1182                expect(result.s1).toBe(base)1183            })1184        })11851186        if (useProxies)1187            it("throws when Object.setPrototypeOf() is used on a draft", () => {1188                produce({}, draft => {1189                    expect(() =>1190                        Object.setPrototypeOf(draft, Array)1191                    ).toThrowErrorMatchingSnapshot()1192                })1193            })11941195        it("supports the 'in' operator", () => {1196            produce(baseState, draft => {1197                // Known property1198                expect("anArray" in draft).toBe(true)1199                expect(Reflect.has(draft, "anArray")).toBe(true)12001201                // Unknown property1202                expect("bla" in draft).toBe(false)1203                expect(Reflect.has(draft, "bla")).toBe(false)12041205                // Known index1206                expect(0 in draft.anArray).toBe(true)1207                expect("0" in draft.anArray).toBe(true)1208                expect(Reflect.has(draft.anArray, 0)).toBe(true)1209                expect(Reflect.has(draft.anArray, "0")).toBe(true)12101211                // Unknown index1212                expect(17 in draft.anArray).toBe(false)1213                expect("17" in draft.anArray).toBe(false)1214                expect(Reflect.has(draft.anArray, 17)).toBe(false)1215                expect(Reflect.has(draft.anArray, "17")).toBe(false)1216            })1217        })12181219        it("'this' should not be bound anymore - 1", () => {1220            const base = {x: 3}1221            const next1 = produce(base, function() {1222                expect(this).toBe(undefined)1223            })1224        })12251226        it("'this' should not be bound anymore - 2", () => {1227            const incrementor = produce(function() {1228                expect(this).toBe(undefined)1229            })1230            incrementor()1231        })12321233        it("should be possible to use dynamic bound this", () => {1234            const world = {1235                counter: {count: 1},1236                inc: produce(function(draft) {1237                    expect(this).toBe(world)1238                    draft.counter.count = this.counter.count + 11239                })1240            }12411242            expect(world.inc(world).counter.count).toBe(2)1243        })12441245        // See here: https://github.com/mweststrate/immer/issues/891246        it("supports the spread operator", () => {1247            const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1248            const result = produce(base, draft => {1249                draft.foo = {x: 1, ...draft.foo, y: 1}1250                draft.bar = [1, ...draft.bar, 1]1251            })1252            expect(result).toEqual({1253                foo: {x: 0, y: 1},1254                bar: [1, 0, 0, 1]1255            })1256        })12571258        it("processes with lodash.set", () => {1259            const base = [{id: 1, a: 1}]1260            const result = produce(base, draft => {1261                lodash.set(draft, "[0].a", 2)1262            })1263            expect(base[0].a).toEqual(1)1264            expect(result[0].a).toEqual(2)1265        })12661267        it("processes with lodash.find", () => {1268            const base = [{id: 1, a: 1}]1269            const result = produce(base, draft => {1270                const obj1 = lodash.find(draft, {id: 1})1271                lodash.set(obj1, "a", 2)1272            })1273            expect(base[0].a).toEqual(1)1274            expect(result[0].a).toEqual(2)1275        })12761277        describe("recipe functions", () => {1278            it("can return a new object", () => {1279                const base = {x: 3}1280                const res = produce(base, d => {1281                    return {x: d.x + 1}1282                })1283                expect(res).not.toBe(base)1284                expect(res).toEqual({x: 4})1285            })12861287            it("can return the draft", () => {1288                const base = {x: 3}1289                const res = produce(base, d => {1290                    d.x = 41291                    return d1292                })1293                expect(res).not.toBe(base)1294                expect(res).toEqual({x: 4})1295            })12961297            it("can return an unmodified child draft", () => {1298                const base = {a: {}}1299                const res = produce(base, d => {1300                    return d.a1301                })1302                expect(res).toBe(base.a)1303            })13041305            // TODO: Avoid throwing if only the child draft was modified.1306            it("cannot return a modified child draft", () => {1307                const base = {a: {}}1308                expect(() => {1309                    produce(base, d => {1310                        d.a.b = 11311                        return d.a1312                    })1313                }).toThrowErrorMatchingSnapshot()1314            })13151316            it("can return a frozen object", () => {1317                const res = deepFreeze([{x: 3}])1318                expect(produce({}, () => res)).toBe(res)1319            })13201321            it("can return an object with two references to another object", () => {1322                const next = produce({}, d => {1323                    const obj = {}1324                    return {obj, arr: [obj]}1325                })1326                expect(next.obj).toBe(next.arr[0])1327            })13281329            it("can return an object with two references to an unmodified draft", () => {1330                const base = {a: {}}1331                const next = produce(base, d => {1332                    return [d.a, d.a]1333                })1334                expect(next[0]).toBe(base.a)1335                expect(next[0]).toBe(next[1])1336            })13371338            it("cannot return an object that references itself", () => {1339                const res = {}1340                res.self = res1341                expect(() => {1342                    produce(res, () => res.self)1343                }).toThrowErrorMatchingSnapshot()1344            })1345        })13461347        describe("async recipe function", () => {1348            it("can modify the draft", () => {1349                const base = {a: 0, b: 0}1350                return produce(base, async d => {1351                    d.a = 11352                    await Promise.resolve()1353                    d.b = 11354                }).then(res => {1355                    expect(res).not.toBe(base)1356                    expect(res).toEqual({a: 1, b: 1})1357                })1358            })13591360            it("works with rejected promises", () => {1361                let draft1362                const base = {a: 0, b: 0}1363                const err = new Error("passed")1364                return produce(base, d => {1365                    draft = d1366                    draft.b = 11367                    return Promise.reject(err)1368                }).then(1369                    () => {1370                        throw "failed"1371                    },1372                    e => {1373                        expect(e).toBe(err)1374                        expect(() => draft.a).toThrowErrorMatchingSnapshot()1375                    }1376                )1377            })13781379            it("supports recursive produce calls after await", () => {1380                const base = {obj: {k: 1}}1381                return produce(base, d => {1382                    const obj = d.obj1383                    delete d.obj1384                    return Promise.resolve().then(() => {1385                        d.a = produce({}, d => {1386                            d.b = obj // Assign a draft owned by the parent scope.1387                        })13881389                        // Auto-freezing is prevented when an unowned draft exists.1390                        expect(Object.isFrozen(d.a)).toBeFalsy()13911392                        // Ensure `obj` is not revoked.1393                        obj.c = 11394                    })1395                }).then(res => {1396                    expect(res).not.toBe(base)1397                    expect(res).toEqual({1398                        a: {b: {k: 1, c: 1}}1399                    })1400                })1401            })1402        })14031404        it("throws when the draft is modified and another object is returned", () => {1405            const base = {x: 3}1406            expect(() => {1407                produce(base, draft => {1408                    draft.x = 41409                    return {x: 5}1410                })1411            }).toThrowErrorMatchingSnapshot()1412        })14131414        it("should fix #117 - 1", () => {1415            const reducer = (state, action) =>1416                produce(state, draft => {1417                    switch (action.type) {1418                        case "SET_STARTING_DOTS":1419                            return draft.availableStartingDots.map(a => a)1420                        default:1421                            break1422                    }1423                })1424            const base = {1425                availableStartingDots: [1426                    {dots: 4, count: 1},1427                    {dots: 3, count: 2},1428                    {dots: 2, count: 3},1429                    {dots: 1, count: 4}1430                ]1431            }1432            const next = reducer(base, {type: "SET_STARTING_DOTS"})1433            expect(next).toEqual(base.availableStartingDots)1434            expect(next).not.toBe(base.availableStartingDots)1435        })14361437        it("should fix #117 - 2", () => {1438            const reducer = (state, action) =>1439                produce(state, draft => {1440                    switch (action.type) {1441                        case "SET_STARTING_DOTS":1442                            return {1443                                dots: draft.availableStartingDots.map(a => a)1444                            }1445                        default:1446                            break1447                    }1448                })1449            const base = {1450                availableStartingDots: [1451                    {dots: 4, count: 1},1452                    {dots: 3, count: 2},1453                    {dots: 2, count: 3},1454                    {dots: 1, count: 4}1455                ]1456            }1457            const next = reducer(base, {type: "SET_STARTING_DOTS"})1458            expect(next).toEqual({dots: base.availableStartingDots})1459        })14601461        it("cannot always detect noop assignments - 0", () => {1462            const baseState = {x: {y: 3}}1463            const nextState = produce(baseState, d => {1464                const a = d.x1465                d.x = a1466            })1467            expect(nextState).toBe(baseState)1468        })14691470        it("cannot always detect noop assignments - 1", () => {1471            const baseState = {x: {y: 3}}1472            const nextState = produce(baseState, d => {1473                const a = d.x1474                d.x = 41475                d.x = a1476            })1477            // Ideally, this should actually be the same instances1478            // but this would be pretty expensive to detect,1479            // so we don't atm1480            expect(nextState).not.toBe(baseState)1481        })14821483        it("cannot always detect noop assignments - 2", () => {1484            const baseState = {x: {y: 3}}1485            const nextState = produce(baseState, d => {1486                const a = d.x1487                const stuff = a.y + 31488                d.x = 41489                d.x = a1490            })1491            // Ideally, this should actually be the same instances1492            // but this would be pretty expensive to detect,1493            // so we don't atm1494            expect(nextState).not.toBe(baseState)1495        })14961497        it("cannot always detect noop assignments - 3", () => {1498            const baseState = {x: 3}1499            const nextState = produce(baseState, d => {1500                d.x = 31501            })1502            expect(nextState).toBe(baseState)1503        })15041505        it("cannot always detect noop assignments - 4", () => {1506            const baseState = {x: 3}1507            const nextState = produce(baseState, d => {1508                d.x = 41509                d.x = 31510            })1511            // Ideally, this should actually be the same instances1512            // but this would be pretty expensive to detect,1513            // so we don't atm1514            expect(nextState).not.toBe(baseState)1515        })15161517        it("cannot produce undefined by returning undefined", () => {1518            const base = 31519            expect(produce(base, () => 4)).toBe(4)1520            expect(produce(base, () => null)).toBe(null)1521            expect(produce(base, () => undefined)).toBe(3)1522            expect(produce(base, () => {})).toBe(3)1523            expect(produce(base, () => nothing)).toBe(undefined)15241525            expect(produce({}, () => undefined)).toEqual({})1526            expect(produce({}, () => nothing)).toBe(undefined)1527            expect(produce(3, () => nothing)).toBe(undefined)15281529            expect(produce(() => undefined)({})).toEqual({})1530            expect(produce(() => nothing)({})).toBe(undefined)1531            expect(produce(() => nothing)(3)).toBe(undefined)1532        })15331534        describe("base state type", () => {1535            testObjectTypes(produce)1536            testLiteralTypes(produce)1537        })15381539        afterEach(() => {1540            expect(baseState).toBe(origBaseState)1541            expect(baseState).toEqual(createBaseState())1542        })15431544        class Foo {}1545        function createBaseState() {1546            const data = {1547                anInstance: new Foo(),1548                anArray: [3, 2, {c: 3}, 1],1549                aMap: new Map([1550                    ["jedi", {name: "Luke", skill: 10}],1551                    ["jediTotal", 42],1552                    ["force", "these aren't the droids you're looking for"]1553                ]),1554                aSet: new Set([1555                    "Luke",1556                    42,1557                    {1558                        jedi: "Yoda"1559                    }1560                ]),1561                aProp: "hi",1562                anObject: {1563                    nested: {1564                        yummie: true1565                    },1566                    coffee: false1567                }1568            }1569            return autoFreeze ? deepFreeze(data) : data1570        }1571    })15721573    describe(`isDraft - ${name}`, () => {1574        it("returns true for object drafts", () => {1575            produce({}, state => {1576                expect(isDraft(state)).toBeTruthy()1577            })1578        })1579        it("returns true for array drafts", () => {1580            produce([], state => {1581                expect(isDraft(state)).toBeTruthy()1582            })1583        })1584        it("returns true for objects nested in object drafts", () => {1585            produce({a: {b: {}}}, state => {1586                expect(isDraft(state.a)).toBeTruthy()1587                expect(isDraft(state.a.b)).toBeTruthy()1588            })1589        })1590        it("returns false for new objects added to a draft", () => {1591            produce({}, state => {1592                state.a = {}1593                expect(isDraft(state.a)).toBeFalsy()1594            })1595        })1596        it("returns false for objects returned by the producer", () => {1597            const object = produce(null, Object.create)1598            expect(isDraft(object)).toBeFalsy()1599        })1600        it("returns false for arrays returned by the producer", () => {1601            const array = produce(null, _ => [])1602            expect(isDraft(array)).toBeFalsy()1603        })1604        it("returns false for object drafts returned by the producer", () => {1605            const object = produce({}, state => state)1606            expect(isDraft(object)).toBeFalsy()1607        })1608        it("returns false for array drafts returned by the producer", () => {1609            const array = produce([], state => state)1610            expect(isDraft(array)).toBeFalsy()1611        })1612    })1613}16141615function testObjectTypes(produce) {1616    class Foo {1617        constructor(foo) {1618            this.foo = foo1619            this[immerable] = true1620        }1621    }1622    const values = {1623        "empty object": {},1624        "plain object": {a: 1, b: 2},1625        "object (no prototype)": Object.create(null),1626        "empty array": [],1627        "plain array": [1, 2],1628        "class instance (draftable)": new Foo(1)1629    }1630    for (const name in values) {1631        const value = values[name]1632        const copy = shallowCopy(value)1633        testObjectType(name, value)1634        testObjectType(name + " (frozen)", Object.freeze(copy))1635    }1636    function testObjectType(name, base) {1637        describe(name, () => {1638            it("creates a draft", () => {1639                produce(base, draft => {1640                    expect(draft).not.toBe(base)1641                    expect(shallowCopy(draft, true)).toEqual(base)1642                })1643            })16441645            it("preserves the prototype", () => {1646                const proto = Object.getPrototypeOf(base)1647                produce(base, draft => {1648                    expect(Object.getPrototypeOf(draft)).toBe(proto)1649                })1650            })16511652            it("returns the base state when no changes are made", () => {1653                expect(produce(base, () => {})).toBe(base)1654            })16551656            it("returns a copy when changes are made", () => {1657                const random = Math.random()1658                const result = produce(base, draft => {1659                    draft[0] = random1660                })1661                expect(result).not.toBe(base)1662                expect(result.constructor).toBe(base.constructor)1663                expect(result[0]).toBe(random)1664            })1665        })1666    }1667}16681669function testLiteralTypes(produce) {1670    class Foo {}1671    const values = {1672        "falsy number": 0,1673        "truthy number": 1,1674        "negative number": -1,1675        NaN: NaN,1676        infinity: 1 / 0,1677        true: true,1678        false: false,1679        "empty string": "",1680        "truthy string": "1",1681        null: null,1682        undefined: undefined,16831684        /**1685         * These objects are treated as literals because Immer1686         * does not know how to draft them.1687         */1688        function: () => {},1689        "regexp object": /.+/g,1690        "boxed number": new Number(0),1691        "boxed string": new String(""),1692        "boxed boolean": new Boolean(),1693        "date object": new Date(),1694        "class instance (not draftable)": new Foo()1695    }1696    for (const name in values) {1697        describe(name, () => {1698            const value = values[name]16991700            it("does not create a draft", () => {1701                produce(value, draft => {1702                    expect(draft).toBe(value)1703                })1704            })17051706            it("returns the base state when no changes are made", () => {1707                expect(produce(value, () => {})).toBe(value)1708            })17091710            if (value && typeof value == "object") {1711                it("does not return a copy when changes are made", () => {1712                    expect(1713                        produce(value, draft => {1714                            draft.foo = true1715                        })1716                    ).toBe(value)1717                })1718            }1719        })1720    }1721}17221723function enumerableOnly(x) {1724    const copy = Array.isArray(x) ? x.slice() : Object.assign({}, x)1725    each(copy, (prop, value) => {1726        if (value && typeof value === "object") {1727            copy[prop] = enumerableOnly(value)1728        }1729    })1730    return copy1731}