Skip to content
Myr

base.js

This file

Path

__tests__/base.js

1,518 lines · 50.6 KiB · JavaScript

Last changed by

fix(tests): base state typealeclarsonbefore adoptiond157d7a

History of this file

Take it

1"use strict"2import produce, {3    setAutoFreeze,4    setUseProxies,5    nothing,6    isDraft7} from "../src/immer"8import deepFreeze from "deep-freeze"9import cloneDeep from "lodash.clonedeep"10import * as lodash from "lodash"1112jest.setTimeout(1000)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, freeze, useListener) {22    describe(`base functionality - ${name}`, () => {23        let baseState24        let origBaseState25        // make sure logic doesn't break when listener is attached26        let listener = useListener ? function() {} : undefined2728        beforeEach(() => {29            setAutoFreeze(freeze)30            setUseProxies(useProxies)31            origBaseState = baseState = createBaseState()32        })3334        it("should return the original without modifications", () => {35            const nextState = produce(baseState, () => {}, listener)36            expect(nextState).toBe(baseState)37        })3839        it("should return the original without modifications when reading stuff", () => {40            const nextState = produce(41                baseState,42                s => {43                    expect(s.aProp).toBe("hi")44                    expect(s.anObject.nested).toMatchObject({yummie: true})45                },46                listener47            )48            expect(nextState).toBe(baseState)49        })5051        it("should return a copy when modifying stuff", () => {52            const nextState = produce(53                baseState,54                s => {55                    s.aProp = "hello world"56                },57                listener58            )59            expect(nextState).not.toBe(baseState)60            expect(baseState.aProp).toBe("hi")61            expect(nextState.aProp).toBe("hello world")62            // structural sharing?63            expect(nextState.nested).toBe(baseState.nested)64        })6566        it("should preserve type", () => {67            const nextState = produce(68                baseState,69                s => {70                    expect(Object.getPrototypeOf(s)).toBe(Object.prototype)71                    expect(Array.isArray(s.anArray)).toBe(true)72                    s.anArray.push(3)73                    s.aProp = "hello world"74                    expect(Object.getPrototypeOf(s)).toBe(Object.prototype)75                    expect(Array.isArray(s.anArray)).toBe(true)76                },77                listener78            )79            expect(Object.getPrototypeOf(nextState)).toBe(Object.prototype)80            expect(Array.isArray(nextState.anArray)).toBe(true)81        })8283        it("deep change bubbles up", () => {84            const nextState = produce(85                baseState,86                s => {87                    s.anObject.nested.yummie = false88                },89                listener90            )91            expect(nextState).not.toBe(baseState)92            expect(nextState.anObject).not.toBe(baseState.anObject)93            expect(baseState.anObject.nested.yummie).toBe(true)94            expect(nextState.anObject.nested.yummie).toBe(false)95            expect(nextState.anArray).toBe(baseState.anArray)96        })9798        it("can add props", () => {99            const nextState = produce(100                baseState,101                s => {102                    s.anObject.cookie = {tasty: true}103                },104                listener105            )106            expect(nextState).not.toBe(baseState)107            expect(nextState.anObject).not.toBe(baseState.anObject)108            expect(nextState.anObject.nested).toBe(baseState.anObject.nested)109            expect(nextState.anObject.cookie).toEqual({tasty: true})110        })111112        it("can delete props", () => {113            const nextState = produce(114                baseState,115                s => {116                    delete s.anObject.nested117                },118                listener119            )120            expect(nextState).not.toBe(baseState)121            expect(nextState.anObject).not.toBe(baseState.anObject)122            expect(nextState.anObject.nested).toBe(undefined)123        })124125        it("ignores single non-modification", () => {126            const nextState = produce(127                baseState,128                s => {129                    s.aProp = "hi"130                },131                listener132            )133            expect(nextState).toBe(baseState)134        })135136        it("processes single modification", () => {137            const nextState = produce(138                baseState,139                s => {140                    s.aProp = "hello"141                    s.aProp = "hi"142                },143                listener144            )145            expect(nextState).not.toBe(baseState)146            expect(nextState).toEqual(baseState)147        })148149        it("processes with for loop", () => {150            const base = [{id: 1, a: 1}, {id: 2, a: 1}]151            const findById = (collection, id) => {152                for (const item of collection) {153                    if (item.id === id) return item154                }155                return null156            }157            const result = produce(base, draft => {158                const obj1 = findById(draft, 1)159                const obj2 = findById(draft, 2)160                obj1.a = 2161                obj2.a = 2162            })163            expect(result[0].a).toEqual(2)164            expect(result[1].a).toEqual(2)165        })166167        it("works with objects without proto", () => {168            const base = Object.create(null)169            base.x = 1170            base.y = Object.create(null)171            base.y.y = 2172            expect(base.__proto__).toBe(undefined)173            const next = produce(174                base,175                draft => {176                    draft.y.z = 3177                    draft.y.y++178                    draft.x++179                },180                listener181            )182            expect(next).toEqual({183                x: 2,184                y: {y: 3, z: 3}185            })186            expect(next.__proto__).toBe(undefined)187        })188189        it("should support reading arrays", () => {190            const nextState = produce(191                baseState,192                s => {193                    s.anArray.slice()194                },195                listener196            )197            expect(nextState.anArray).toBe(baseState.anArray)198            expect(nextState).toBe(baseState)199        })200201        it("should support changing arrays", () => {202            const nextState = produce(203                baseState,204                s => {205                    s.anArray[3] = true206                },207                listener208            )209            expect(nextState).not.toBe(baseState)210            expect(nextState.anArray).not.toBe(baseState.anArray)211            expect(nextState.anArray[3]).toEqual(true)212        })213214        it("should support changing arrays - 2", () => {215            const nextState = produce(216                baseState,217                s => {218                    s.anArray.splice(1, 1, "a", "b")219                },220                listener221            )222            expect(nextState).not.toBe(baseState)223            expect(nextState.anArray).not.toBe(baseState.anArray)224225            expect(enumerableOnly(nextState.anArray)).toEqual([226                3,227                "a",228                "b",229                {c: 3},230                1231            ])232        })233234        it("can delete array items", () => {235            const nextState = produce(236                baseState,237                s => {238                    s.anArray.length = 3239                },240                listener241            )242            expect(nextState).not.toBe(baseState)243            expect(nextState.anObject).toBe(baseState.anObject)244            expect(nextState.anArray).not.toBe(baseState.anArray)245            expect(nextState.anArray).toEqual([3, 2, {c: 3}])246        })247248        it("should support sorting arrays", () => {249            const nextState = produce(250                baseState,251                s => {252                    s.anArray[2].c = 4253                    s.anArray.sort()254                    s.anArray[3].c = 5255                },256                listener257            )258            expect(nextState).not.toBe(baseState)259            expect(nextState.anArray).not.toBe(baseState.anArray)260            expect(enumerableOnly(nextState.anArray)).toEqual([1, 2, 3, {c: 5}])261        })262263        it("should expose property descriptors", () => {264            const nextState = produce(265                [],266                s => {267                    expect(Object.getOwnPropertyDescriptor(s, 0)).toBe(268                        undefined269                    )270                    s.unshift("x")271                    expect(Object.getOwnPropertyDescriptor(s, 0)).toEqual({272                        configurable: true,273                        enumerable: true,274                        value: "x",275                        writable: true276                    })277                    expect(s.length).toBe(1)278                    expect(s[0] === "x").toBe(true)279                },280                listener281            )282            expect(nextState).toEqual(["x"])283            expect(Object.getOwnPropertyDescriptor(nextState, 0)).toEqual({284                configurable: !freeze,285                enumerable: true,286                value: "x",287                writable: !freeze288            })289        })290291        it("should support sorting arrays - 2", () => {292            const nextState = produce(293                baseState,294                s => {295                    s.anArray.unshift("x")296                    s.anArray[3].c = 4297                    s.anArray.sort()298                    s.anArray[3].c = 5299                    s.anArray.unshift("y")300                },301                listener302            )303            expect(nextState).not.toBe(baseState)304            expect(nextState.anArray).not.toBe(baseState.anArray)305            expect(enumerableOnly(nextState.anArray)).toEqual([306                "y",307                1,308                2,309                3,310                {c: 5},311                "x"312            ])313        })314315        it("should updating inside arrays", () => {316            const nextState = produce(317                baseState,318                s => {319                    s.anArray[2].test = true320                },321                listener322            )323            expect(nextState).not.toBe(baseState)324            expect(nextState.anArray).not.toBe(baseState.anArray)325            expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])326        })327328        it("can rename nested objects (no changes)", () => {329            const nextState = produce(330                baseState,331                s => {332                    const obj = s.anObject333                    delete s.anObject334                    s.renamed = obj335                },336                listener337            )338            expect(nextState).not.toBe(baseState)339            expect(nextState.anArray).toBe(baseState.anArray)340            expect(nextState.renamed.nested).toBe(baseState.anObject.nested)341            expect(enumerableOnly(nextState)).toEqual({342                anArray: [3, 2, {c: 3}, 1],343                aProp: "hi",344                renamed: {345                    nested: {346                        yummie: true347                    },348                    coffee: false349                }350            })351        })352353        // Very similar to the test before, but the reused object has one354        // property changed, one added, and one removed.355        it("can rename nested objects (with changes)", () => {356            const nextState = produce(357                baseState,358                s => {359                    const obj = s.anObject360                    delete s.anObject361362                    obj.coffee = true // change363                    obj.nested.yummy = true // add364                    delete obj.nested.yummie // delete365366                    s.renamed = obj367                },368                listener369            )370            expect(nextState).not.toBe(baseState)371            expect(nextState.anArray).toBe(baseState.anArray)372            expect(nextState.renamed.nested).not.toBe(baseState.anObject.nested)373            expect(enumerableOnly(nextState)).toEqual({374                anArray: [3, 2, {c: 3}, 1],375                aProp: "hi",376                renamed: {377                    nested: {378                        yummy: true379                    },380                    coffee: true381                }382            })383        })384385        it("can nest a draft in a new object (no changes)", () => {386            const nextState = produce(387                baseState,388                s => {389                    s.foo = {bar: s.anObject}390                    delete s.anObject391                },392                listener393            )394            expect(nextState).not.toBe(baseState)395            expect(nextState.foo.bar).toBe(baseState.anObject)396        })397398        it("can nest a draft in a new object (with changes)", () => {399            const nextState = produce(400                baseState,401                s => {402                    const obj = s.anObject403                    delete s.anObject404405                    obj.coffee = true // change406                    obj.nested.yummy = true // add407                    delete obj.nested.yummie // delete408409                    s.foo = {bar: obj}410                },411                listener412            )413            expect(nextState).not.toBe(baseState)414            expect(nextState.foo.bar).not.toBe(baseState.anObject)415            expect(nextState.foo).toEqual({416                bar: {417                    coffee: true,418                    nested: {yummy: true}419                }420            })421        })422423        it("should allow setting to undefined a defined draft property", () => {424            const nextState = produce(425                baseState,426                s => {427                    s.aProp = undefined428                },429                listener430            )431            expect(nextState).not.toBe(baseState)432            expect(baseState.aProp).toBe("hi")433            expect(nextState.aProp).toBe(undefined)434        })435436        // ES implementation does't protect against all outside modifications, just some..437        if (useProxies) {438            it("should revoke the proxy of the baseState after immer function is executed", () => {439                let proxy440                const nextState = produce(441                    baseState,442                    s => {443                        proxy = s444                        s.aProp = "hello"445                    },446                    listener447                )448                expect(nextState).not.toBe(baseState)449                expect(baseState.aProp).toBe("hi")450                expect(nextState.aProp).toBe("hello")451452                expect(() => {453                    proxy.aProp = "Hallo"454                }).toThrowError(/revoked/)455                expect(() => {456                    const aProp = proxy.aProp457                }).toThrowError(/revoked/)458459                expect(nextState).not.toBe(baseState)460                expect(baseState.aProp).toBe("hi")461                expect(nextState.aProp).toBe("hello")462            })463        }464465        it("should revoke the proxy of the baseState after immer function is executed - 2", () => {466            let proxy467            const nextState = produce(468                baseState,469                s => {470                    proxy = s.anObject471                },472                listener473            )474            expect(nextState).toBe(baseState)475            expect(() => {476                // In ES5 implemenation only protects existing props, but alas..477                proxy.coffee = "Hallo"478            }).toThrowError(/revoked/)479            expect(() => {480                const test = proxy.coffee481            }).toThrowError(/revoked/)482        })483484        it("should reflect all changes made in the draft immediately", () => {485            produce(486                baseState,487                draft => {488                    draft.anArray[0] = 5489                    draft.anArray.unshift("test")490                    // sliced here; jest will also compare non-enumerable keys, which would include the immer Symbols491                    expect(draft.anArray.slice()).toMatchObject([492                        "test",493                        5,494                        2,495                        {c: 3},496                        1497                    ])498                    draft.stuffz = "coffee"499                    expect(draft.stuffz).toBe("coffee")500                },501                listener502            )503        })504505        it("should be able to get property descriptors from objects", () => {506            produce(507                {a: 1},508                draft => {509                    expect("a" in draft).toBe(true)510                    expect("b" in draft).toBe(false)511                    expect(512                        Reflect.ownKeys(draft).filter(513                            x => typeof x === "string"514                        )515                    ).toEqual(["a"])516517                    expect(518                        Object.getOwnPropertyDescriptor(draft, "a")519                    ).toMatchObject({520                        configurable: true,521                        enumerable: true522                    })523                    draft.a = 2524                    expect(525                        Object.getOwnPropertyDescriptor(draft, "a")526                    ).toMatchObject({527                        configurable: true,528                        enumerable: true529                    })530                    expect(531                        Object.getOwnPropertyDescriptor(draft, "b")532                    ).toBeUndefined()533                    draft.b = 2534                    expect(535                        Object.getOwnPropertyDescriptor(draft, "b")536                    ).toMatchObject({537                        configurable: true,538                        enumerable: true539                    })540                    expect("a" in draft).toBe(true)541                    expect("b" in draft).toBe(true)542                    expect(543                        Reflect.ownKeys(draft).filter(544                            x => typeof x === "string"545                        )546                    ).toEqual(["a", "b"])547                },548                listener549            )550        })551552        it("should be able to get property descriptors from arrays", () => {553            produce(554                [1],555                draft => {556                    expect(0 in draft).toBe(true)557                    expect(1 in draft).toBe(false)558                    expect("0" in draft).toBe(true)559                    expect("1" in draft).toBe(false)560                    expect(length in draft).toBe(true)561                    expect(562                        Reflect.ownKeys(draft).filter(563                            x => typeof x === "string"564                        )565                    ).toEqual(["0", "length"])566567                    expect(568                        Object.getOwnPropertyDescriptor(draft, "length")569                    ).toMatchObject({570                        configurable: false,571                        enumerable: false572                    })573                    draft[0] = 2574                    expect(575                        Object.getOwnPropertyDescriptor(draft, 0)576                    ).toMatchObject({577                        configurable: true,578                        enumerable: true579                    })580                    expect(581                        Object.getOwnPropertyDescriptor(draft, 0)582                    ).toMatchObject({583                        configurable: true,584                        enumerable: true585                    })586                    expect(587                        Object.getOwnPropertyDescriptor(draft, 1)588                    ).toBeUndefined()589                    draft[1] = 2590                    expect(591                        Object.getOwnPropertyDescriptor(draft, 1)592                    ).toMatchObject({593                        configurable: true,594                        enumerable: true595                    })596                    expect(597                        Reflect.ownKeys(draft).filter(598                            x => typeof x === "string"599                        )600                    ).toEqual(["0", "1", "length"])601                },602                listener603            )604        })605606        if (useProxies === true) {607            it("should not be possible to set property descriptors", () => {608                expect(() => {609                    produce(610                        {},611                        draft => {612                            Object.defineProperty(draft, "xx", {613                                enumerable: true,614                                writeable: true,615                                value: 2616                            })617                        },618                        listener619                    )620                }).toThrowError(/not support/)621            })622623            it("should not be possible to add properties to arrays", () => {624                expect(() => {625                    produce([], d => {626                        d.x = 3627                    })628                }).toThrow(629                    "Immer does not support setting non-numeric properties on arrays"630                )631            })632633            it("should not be possible to remove properties from arrays", () => {634                expect(() => {635                    const base = []636                    base.x = 7637                    produce(base, d => {638                        delete d.x639                    })640                }).toThrow(641                    "Immer does not support deleting properties from arrays"642                )643            })644        }645646        it("non-numeric array properties will be lost", () => {647            const base = []648            base.x = 7649            const next = produce(base, d => {650                d.push(3)651            })652            expect(next.x).toBe(undefined)653        })654655        it("should not throw error, see #53 - 1", () => {656            const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}657            const result = produce(658                base,659                draft => {660                    draft.arr = draft.arr.filter(item => item.count > 2)661                },662                listener663            )664            expect(result.arr[0].count).toEqual(3)665            expect(result).toEqual({666                arr: [{count: 3}]667            })668            expect(result.arr[0]).toBe(base.arr[2])669        })670671        it("should not throw error, see #53 - 2", () => {672            const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}673            const result = produce(674                base,675                draft => {676                    draft.newArr = draft.arr.filter(item => item.count > 2)677                },678                listener679            )680            expect(result.newArr[0].count).toEqual(3)681            expect(result.arr).toBe(base.arr)682            expect(result).toEqual({683                arr: [684                    {685                        count: 1686                    },687                    {688                        count: 2689                    },690                    {691                        count: 3692                    }693                ],694                newArr: [695                    {696                        count: 3697                    }698                ]699            })700            expect(result.newArr[0]).toBe(base.arr[2])701            expect(result.arr[2]).toBe(base.arr[2])702        })703704        it("should not throw error, see #53 - 3", () => {705            const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}706            const result = produce(707                base,708                draft => {709                    draft.newArr = draft.arr.filter(item => item.count > 2)710                    delete draft.arr711                },712                listener713            )714            expect(result.newArr[0].count).toEqual(3)715            expect(result).toEqual({716                newArr: [{count: 3}]717            })718            expect(result.newArr[0]).toBe(base.arr[2])719        })720721        it("should not throw error, see #53 - 4", () => {722            const base = {bear: {age: 10}}723            const result = produce(724                base,725                draft => {726                    draft.bear.legs = 4727                    draft.room = {elephant: {kiddo: draft.bear}}728                },729                listener730            )731            expect(result).toEqual({732                bear: {age: 10, legs: 4},733                room: {elephant: {kiddo: {age: 10, legs: 4}}}734            })735736            const result2 = produce(result, draft => {737                draft.bear.age = 11738                draft.room.elephant.kiddo.legs = 5739            })740            expect(result2).toEqual({741                bear: {age: 11, legs: 4},742                room: {elephant: {kiddo: {age: 10, legs: 5}}}743            })744        })745746        it("should not throw error #78", () => {747            const base = {748                arr: [749                    {750                        id: "100",751                        arr: [{id: "1", no: 1}, {id: "2", no: 2}]752                    },753                    {id: "3", no: 3}754                ]755            }756            const result = produce(base, draft => {757                const base = draft.arr[0]758                draft.arr = draft.arr.slice(0, 1)759                const newArr = {760                    id: "101",761                    arr: [base, {id: "3"}]762                }763                draft.arr.splice(0, 1, newArr)764                draft.arr[0].arr[1].no = 3765            })766            expect(result).toEqual({767                arr: [768                    {769                        id: "101",770                        arr: [771                            {772                                id: "100",773                                arr: [{id: "1", no: 1}, {id: "2", no: 2}]774                            },775                            {id: "3", no: 3}776                        ]777                    }778                ]779            })780        })781782        it("should not throw error #78 - 2", () => {783            const base = {784                arr: [{count: 1}, {count: 2}]785            }786            const result = produce(base, draft => {787                draft.arr = [draft.arr[1]]788                draft.arr[0].count = 1789            })790            expect(result).toEqual({791                arr: [{count: 1}]792            })793        })794795        it("should handle constructor correctly", () => {796            const base = {797                arr: new Array(),798                obj: new Object()799            }800            const result = produce(base, draft => {801                draft.arrConstructed = draft.arr.constructor(1)802                draft.objConstructed = draft.obj.constructor(1)803            })804            expect(result.arrConstructed).toEqual(new Array().constructor(1))805            expect(result.objConstructed).toEqual(new Object().constructor(1))806        })807808        it("should handle dates correctly", () => {809            const data = {date: new Date()}810            const next = produce(data, draft => {811                draft.x = true812            })813            expect(next).toEqual({x: true, date: data.date})814            expect(next.date).toBe(data.date)815            const next2 = produce(next, draft => {816                draft.date.setYear(2015)817            })818            // This still holds; because produce won't proxy Date objects819            // and the original is actually modified!820            expect(next2).toEqual({x: true, date: data.date})821            expect(next2.date).toBe(next.date)822            expect(next2.date).toBe(data.date)823            expect(next2).toBe(next)824        })825826        it("should handle equality correctly - 1", () => {827            const base = {828                y: 3 / 0,829                z: NaN830            }831            const next = produce(base, draft => {832                draft.y = 4 / 0833                draft.z = NaN834            })835            expect(next).toEqual(base)836            expect(next).toBe(base)837        })838839        it("should handle equality correctly - 2", () => {840            const base = {841                x: -0842            }843            const next = produce(base, draft => {844                draft.x = +1845            })846            expect(next).not.toEqual(base)847            expect(next).not.toBe(base)848        })849850        describe("nested immer.produce() call", () => {851            describe("with non-draft object", () => {852                // This test ensures the global state used to manage proxies is853                // never left in a corrupted state by a nested `produce` call.854                it("never affects its parent producer implicitly", () => {855                    const bear = {paw: {honey: true}}856                    const next = produce(857                        bear,858                        draft => {859                            const paw2 = produce(bear.paw, draft => {860                                draft.honey = false861                            })862                            expect(paw2.honey).toBe(false)863                            expect(draft.paw.honey).toBe(true) // effects should not be visible outside864                        },865                        listener866                    )867                    expect(next.paw.honey).toBe(true)868                    expect(next).toBe(bear)869                })870871                it("returns a normal object", () => {872                    const bear = {paw: {honey: true}}873                    const next = produce(874                        bear,875                        draft => {876                            const paw2 = produce(bear.paw, draft => {877                                draft.honey = false878                            })879                            expect(paw2.honey).toBe(false)880                            expect(draft.paw.honey).toBe(true)881                            draft.paw = paw2882                            expect(draft.paw.honey).toBe(false)883                        },884                        listener885                    )886                    expect(next.paw.honey).toBe(false)887                    expect(next).not.toBe(bear)888                })889            })890891            describe("with a draft object", () => {892                it("always reuses the draft", () => {893                    const bear = {paw: {honey: true}}894                    const next = produce(895                        bear,896                        bear => {897                            const paw2 = produce(bear.paw, paw => {898                                expect(paw).toBe(bear.paw)899                                paw.honey = false900                            })901                            expect(paw2).toBe(bear.paw)902                            expect(paw2.honey).toBe(false)903                            expect(bear.paw.honey).toBe(false)904                        },905                        listener906                    )907                    expect(next.paw.honey).toBe(false)908                    expect(next).not.toBe(bear)909                })910            })911        })912913        it("should not try to change immutable data, see #66", () => {914            const user = require("./test-data")915916            const base = {}917            const next = produce(918                base,919                draft => {920                    draft.user = user921                },922                listener923            )924            expect(next.user).toBe(user)925            expect(next).not.toBe(base)926            expect(next.user).toEqual(user)927        })928929        it("should not try to change immutable data, see #66 - 2", () => {930            const user = deepFreeze(cloneDeep(require("./test-data")))931932            const base = {}933            const next = produce(934                base,935                draft => {936                    draft.user = user937                },938                listener939            )940            expect(next.user).toBe(user)941            expect(next).not.toBe(base)942            expect(next.user).toEqual(user)943        })944945        it("should structurally share identical objects in the tree", () => {946            const base = {bear: {legs: 4}, eagle: {legs: 3}}947            const next = produce(948                base,949                draft => {950                    const animal = draft.bear951                    animal.legs = animal.legs + 1952                    draft.bear = animal953                    draft.eagle = animal954                    draft.cow = animal955                    draft.kiddo = animal956                },957                listener958            )959            expect(next).toEqual({960                bear: {legs: 5},961                eagle: {legs: 5},962                cow: {legs: 5},963                kiddo: {legs: 5}964            })965            expect(next.bear).toBe(next.cow)966            expect(next.kiddo).toBe(next.cow)967        })968969        if (useProxies)970            it("should not allow changing prototype", () => {971                produce(972                    {},973                    draft => {974                        expect(() =>975                            Object.setPrototypeOf(draft, Array)976                        ).toThrow(/does not support `setPrototype/)977                    },978                    listener979                )980            })981982        it("'in' should work", () => {983            produce(984                createBaseState(),985                draft => {986                    expect("anArray" in draft).toBe(true)987                    expect(Reflect.has(draft, "anArray")).toBe(true)988989                    expect("bla" in draft).toBe(false)990                    expect(Reflect.has(draft, "bla")).toBe(false)991992                    expect(0 in draft.anArray).toBe(true)993                    expect("0" in draft.anArray).toBe(true)994                    expect(Reflect.has(draft.anArray, 0)).toBe(true)995                    expect(Reflect.has(draft.anArray, "0")).toBe(true)996997                    expect(17 in draft.anArray).toBe(false)998                    expect("17" in draft.anArray).toBe(false)999                    expect(Reflect.has(draft.anArray, 17)).toBe(false)1000                    expect(Reflect.has(draft.anArray, "17")).toBe(false)1001                },1002                listener1003            )1004        })10051006        it("'this' should work - 1", () => {1007            const base = {x: 3}1008            const next1 = produce(1009                base,1010                function() {1011                    this.x = 41012                },1013                listener1014            )1015            expect(next1).not.toBe(base)1016            expect(next1.x).toBe(4)1017        })10181019        it("'this' should work - 1", () => {1020            const base = {x: 3}1021            const incrementor = produce(function() {1022                this.x = 41023            })1024            const next1 = incrementor(base)1025            expect(next1).not.toBe(base)1026            expect(next1.x).toBe(4)1027        })10281029        it("issue #89", () => {1030            const state = {1031                users: {1032                    existingID: {1033                        loading: false,1034                        value: "val"1035                    }1036                }1037            }1038            const nextState = produce(1039                state,1040                draft => {1041                    draft.users.existingID = {1042                        ...draft.users.existingID,1043                        loading: true1044                    }1045                },1046                listener1047            )1048            expect(nextState).toEqual({1049                users: {1050                    existingID: {1051                        loading: true,1052                        value: "val"1053                    }1054                }1055            })1056        })10571058        it("processes with lodash.set", () => {1059            const base = [{id: 1, a: 1}]1060            const result = produce(1061                base,1062                draft => {1063                    lodash.set(draft, "[0].a", 2)1064                },1065                listener1066            )1067            expect(base[0].a).toEqual(1)1068            expect(result[0].a).toEqual(2)1069        })10701071        it("processes with lodash.find", () => {1072            const base = [{id: 1, a: 1}]1073            const result = produce(1074                base,1075                draft => {1076                    const obj1 = lodash.find(draft, {id: 1})1077                    lodash.set(obj1, "a", 2)1078                },1079                listener1080            )1081            expect(base[0].a).toEqual(1)1082            expect(result[0].a).toEqual(2)1083        })10841085        it("can produce from no state", () => {1086            expect(1087                produce(1088                    3,1089                    draft => {1090                        expect(draft).toBe(3)1091                        return 51092                    },1093                    listener1094                )1095            ).toBe(5)1096        })10971098        it("can return something new ", () => {1099            const base = {x: 3}1100            const res = produce(1101                base,1102                draft => {1103                    return {x: draft.x + 1}1104                },1105                listener1106            )1107            expect(res).not.toBe(base)1108            expect(res).toEqual({x: 4})1109        })11101111        it("can return the draft new ", () => {1112            const base = {x: 3}1113            const res = produce(1114                base,1115                draft => {1116                    draft.x = 41117                    return draft1118                },1119                listener1120            )1121            expect(res).not.toBe(base)1122            expect(res).toEqual({x: 4})1123        })11241125        it("should throw if modifying the draft and returning something new", () => {1126            const base = {x: 3}1127            expect(() => {1128                produce(1129                    base,1130                    draft => {1131                        draft.x = 41132                        return {x: 5}1133                    },1134                    listener1135                )1136            }).toThrow(/An immer producer returned a new value/)1137        })11381139        it("should fix #116", () => {1140            const nextState = produce(1141                [1, 2, 3],1142                s => {1143                    s.pop()1144                    s.push(100)1145                },1146                listener1147            )1148            expect(nextState).toEqual([1, 2, 100])1149        })11501151        it("should fix #117", () => {1152            const reducer = (state, action) =>1153                produce(1154                    state,1155                    draft => {1156                        switch (action.type) {1157                            case "SET_STARTING_DOTS":1158                                return draft.availableStartingDots.map(a => a)1159                            default:1160                                break1161                        }1162                    },1163                    listener1164                )1165            const base = {1166                availableStartingDots: [1167                    {dots: 4, count: 1},1168                    {dots: 3, count: 2},1169                    {dots: 2, count: 3},1170                    {dots: 1, count: 4}1171                ]1172            }1173            const next = reducer(base, {type: "SET_STARTING_DOTS"})1174            expect(next).toEqual(base.availableStartingDots)1175            expect(next).not.toBe(base.availableStartingDots)1176        })11771178        it("should fix #117 - 2", () => {1179            const reducer = (state, action) =>1180                produce(1181                    state,1182                    draft => {1183                        switch (action.type) {1184                            case "SET_STARTING_DOTS":1185                                return {1186                                    dots: draft.availableStartingDots.map(1187                                        a => a1188                                    )1189                                }1190                            default:1191                                break1192                        }1193                    },1194                    listener1195                )1196            const base = {1197                availableStartingDots: [1198                    {dots: 4, count: 1},1199                    {dots: 3, count: 2},1200                    {dots: 2, count: 3},1201                    {dots: 1, count: 4}1202                ]1203            }1204            const next = reducer(base, {type: "SET_STARTING_DOTS"})1205            expect(next).toEqual({dots: base.availableStartingDots})1206        })12071208        it("should return an unmodified primitive baseState (#148)", () => {1209            const baseState = "some string"1210            const nextState = produce(1211                baseState,1212                () => {1213                    /* no modification  */1214                },1215                listener1216            )1217            expect(nextState).toBe(baseState)1218        })12191220        it("should return an unmodified null baseState (#148)", () => {1221            const baseState = null1222            const nextState = produce(1223                baseState,1224                () => {1225                    /* no modification  */1226                },1227                listener1228            )1229            expect(nextState).toBe(baseState)1230        })12311232        it("should not detect noop assignments - 0", () => {1233            const baseState = {x: {y: 3}}1234            const nextState = produce(1235                baseState,1236                d => {1237                    const a = d.x1238                    d.x = a1239                },1240                listener1241            )1242            expect(nextState).toBe(baseState)1243        })12441245        it("should not detect noop assignments - 1", () => {1246            const baseState = {x: {y: 3}}1247            const nextState = produce(1248                baseState,1249                d => {1250                    const a = d.x1251                    d.x = 41252                    d.x = a1253                },1254                listener1255            )1256            // Ideally, this should actually be the same instances1257            // but this would be pretty expensive to detect,1258            // so we don't atm1259            expect(nextState).not.toBe(baseState)1260        })12611262        it("should not detect noop assignments - 2", () => {1263            const baseState = {x: {y: 3}}1264            const nextState = produce(1265                baseState,1266                d => {1267                    const a = d.x1268                    const stuff = a.y + 31269                    d.x = 41270                    d.x = a1271                },1272                listener1273            )1274            // Ideally, this should actually be the same instances1275            // but this would be pretty expensive to detect,1276            // so we don't atm1277            expect(nextState).not.toBe(baseState)1278        })12791280        it("should not detect noop assignments - 3", () => {1281            const baseState = {x: 3}1282            const nextState = produce(1283                baseState,1284                d => {1285                    d.x = 31286                },1287                listener1288            )1289            expect(nextState).toBe(baseState)1290        })12911292        it("should not detect noop assignments - 4", () => {1293            const baseState = {x: 3}1294            const nextState = produce(1295                baseState,1296                d => {1297                    d.x = 41298                    d.x = 31299                },1300                listener1301            )1302            // Ideally, this should actually be the same instances1303            // but this would be pretty expensive to detect,1304            // so we don't atm1305            expect(nextState).not.toBe(baseState)1306        })13071308        it("immer should have no dependencies", () => {1309            expect(require("../package.json").dependencies).toEqual(undefined)1310        })13111312        it("#174", () => {1313            const nextState = produce([1, 2, 3], s => {1314                s.pop()1315                s.push(100)1316            })1317            expect(nextState).toEqual([1, 2, 100])1318        })13191320        it("#195 should be able to find items", () => {1321            const state = {1322                items: [1323                    {1324                        id: 0,1325                        task: "drink milk"1326                    },1327                    {id: 1, task: "eat cookie"}1328                ]1329            }1330            produce(state, draft => {1331                expect(draft.items.find(({id}) => id === 1).task).toBe(1332                    "eat cookie"1333                )1334            })1335        })13361337        it("allows a function as the base state", () => {1338            let fn = () => {}1339            expect(1340                produce(fn, draft => {1341                    expect(fn).toBe(draft)1342                })1343            ).toBe(fn)1344        })13451346        it("cannot return and produce undefined!", () => {1347            const base = 31348            expect(produce(base, () => 4)).toBe(4)1349            expect(produce(base, () => null)).toBe(null)1350            expect(produce(base, () => undefined)).toBe(3)1351            expect(produce(base, () => {})).toBe(3)1352            expect(produce(base, () => nothing)).toBe(undefined)13531354            expect(produce({}, () => undefined)).toEqual({})1355            expect(produce({}, () => nothing)).toBe(undefined)1356            expect(produce(3, () => nothing)).toBe(undefined)13571358            expect(produce(() => undefined)({})).toEqual({})1359            expect(produce(() => nothing)({})).toBe(undefined)1360            expect(produce(() => nothing)(3)).toBe(undefined)1361        })13621363        // TODO: use fuzz testing1364        {1365            class Foo {}1366            const primitives = {1367                "falsy number": 0,1368                "truthy number": 1,1369                "negative number": -1,1370                infinity: 1 / 0,1371                true: true,1372                false: false,1373                "empty string": "",1374                "truthy string": "1",1375                null: null,1376                undefined: undefined,13771378                /**1379                 * These objects are treated as primitives because Immer1380                 * chooses not to make drafts for them.1381                 */1382                "regexp object": /.+/g,1383                "boxed number": new Number(0),1384                "boxed string": new String(""),1385                "boxed boolean": new Boolean(),1386                "date object": new Date(),1387                "class instance": new Foo()1388            }1389            for (const name in primitives) {1390                describe("base state type - " + name, () => {1391                    const value = primitives[name]1392                    it("does not create a draft", () => {1393                        produce(value, draft => {1394                            expect(draft).toBe(value)1395                        })1396                    })1397                    it("returns the same value when the producer returns undefined", () => {1398                        expect(produce(value, () => {})).toBe(value)1399                    })1400                    if (value && typeof value == "object") {1401                        it("does not return a copy when the producer makes changes", () => {1402                            expect(1403                                produce(value, draft => {1404                                    draft.foo = true1405                                })1406                            ).toBe(value)1407                        })1408                    }1409                })1410            }1411            const objects = {1412                "empty object": {},1413                "plain object": {a: 1, b: {c: 1}},1414                "frozen object": Object.freeze({}),1415                "null-prototype object": Object.create(null),1416                "frozen null-prototype object": Object.freeze(1417                    Object.create(null)1418                ),1419                "empty array": [],1420                "plain array": [1, [2, [3, []]]],1421                "frozen array": Object.freeze([])1422            }1423            for (const name in objects) {1424                describe("base state type - " + name, () => {1425                    const value = objects[name]1426                    it("creates a draft", () => {1427                        produce(value, draft => {1428                            expect(draft).not.toBe(value)1429                            expect(enumerableOnly(draft)).toEqual(value)1430                        })1431                    })1432                    it("returns the same value when the producer does nothing", () => {1433                        expect(produce(value, () => {})).toBe(value)1434                    })1435                    it("returns a copy when changes are made", () => {1436                        const random = Math.random()1437                        const result = produce(value, draft => {1438                            draft[0] = random1439                        })1440                        expect(result).not.toBe(value)1441                        expect(result.constructor).toBe(value.constructor)1442                        expect(result[0]).toBe(random)1443                    })1444                })1445            }1446        }14471448        afterEach(() => {1449            expect(baseState).toBe(origBaseState)1450            expect(baseState).toEqual(createBaseState())1451        })14521453        function createBaseState() {1454            const data = {1455                anArray: [3, 2, {c: 3}, 1],1456                aProp: "hi",1457                anObject: {1458                    nested: {1459                        yummie: true1460                    },1461                    coffee: false1462                }1463            }1464            return freeze ? deepFreeze(data) : data1465        }1466    })14671468    describe(`isDraft - ${name}`, () => {1469        beforeAll(() => {1470            setAutoFreeze(freeze)1471            setUseProxies(useProxies)1472        })14731474        it("returns true for object drafts", () => {1475            produce({}, state => {1476                expect(isDraft(state)).toBeTruthy()1477            })1478        })1479        it("returns true for array drafts", () => {1480            produce([], state => {1481                expect(isDraft(state)).toBeTruthy()1482            })1483        })1484        it("returns true for objects nested in object drafts", () => {1485            produce({a: {b: {}}}, state => {1486                expect(isDraft(state.a)).toBeTruthy()1487                expect(isDraft(state.a.b)).toBeTruthy()1488            })1489        })1490        it("returns false for new objects added to a draft", () => {1491            produce({}, state => {1492                state.a = {}1493                expect(isDraft(state.a)).toBeFalsy()1494            })1495        })1496        it("returns false for objects returned by the producer", () => {1497            const object = produce(null, Object.create)1498            expect(isDraft(object)).toBeFalsy()1499        })1500        it("returns false for arrays returned by the producer", () => {1501            const array = produce(null, _ => [])1502            expect(isDraft(array)).toBeFalsy()1503        })1504        it("returns false for object drafts returned by the producer", () => {1505            const object = produce({}, state => state)1506            expect(isDraft(object)).toBeFalsy()1507        })1508        it("returns false for array drafts returned by the producer", () => {1509            const array = produce([], state => state)1510            expect(isDraft(array)).toBeFalsy()1511        })1512    })1513}15141515function enumerableOnly(x) {1516    // this can be done better...1517    return JSON.parse(JSON.stringify(x))1518}