Skip to content
Myr

base.js

This file

Path

__tests__/base.js

1,537 lines · 51.2 KiB · JavaScript

Last changed by

test: deleting props added in the produceraleclarsonbefore adoption691e73b

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        // Found by: https://github.com/mweststrate/immer/pull/267126        it("can delete props added in the producer", () => {127            const nextState = produce(128                baseState,129                s => {130                    s.anObject.test = true131                    delete s.anObject.test132                },133                listener134            )135            if (useProxies) {136                expect(nextState).not.toBe(baseState)137                expect(nextState).toEqual(baseState)138            } else {139                // The copy is avoided in ES5.140                expect(nextState).toBe(baseState)141            }142        })143144        it("ignores single non-modification", () => {145            const nextState = produce(146                baseState,147                s => {148                    s.aProp = "hi"149                },150                listener151            )152            expect(nextState).toBe(baseState)153        })154155        it("processes single modification", () => {156            const nextState = produce(157                baseState,158                s => {159                    s.aProp = "hello"160                    s.aProp = "hi"161                },162                listener163            )164            expect(nextState).not.toBe(baseState)165            expect(nextState).toEqual(baseState)166        })167168        it("processes with for loop", () => {169            const base = [{id: 1, a: 1}, {id: 2, a: 1}]170            const findById = (collection, id) => {171                for (const item of collection) {172                    if (item.id === id) return item173                }174                return null175            }176            const result = produce(base, draft => {177                const obj1 = findById(draft, 1)178                const obj2 = findById(draft, 2)179                obj1.a = 2180                obj2.a = 2181            })182            expect(result[0].a).toEqual(2)183            expect(result[1].a).toEqual(2)184        })185186        it("works with objects without proto", () => {187            const base = Object.create(null)188            base.x = 1189            base.y = Object.create(null)190            base.y.y = 2191            expect(base.__proto__).toBe(undefined)192            const next = produce(193                base,194                draft => {195                    draft.y.z = 3196                    draft.y.y++197                    draft.x++198                },199                listener200            )201            expect(next).toEqual({202                x: 2,203                y: {y: 3, z: 3}204            })205            expect(next.__proto__).toBe(undefined)206        })207208        it("should support reading arrays", () => {209            const nextState = produce(210                baseState,211                s => {212                    s.anArray.slice()213                },214                listener215            )216            expect(nextState.anArray).toBe(baseState.anArray)217            expect(nextState).toBe(baseState)218        })219220        it("should support changing arrays", () => {221            const nextState = produce(222                baseState,223                s => {224                    s.anArray[3] = true225                },226                listener227            )228            expect(nextState).not.toBe(baseState)229            expect(nextState.anArray).not.toBe(baseState.anArray)230            expect(nextState.anArray[3]).toEqual(true)231        })232233        it("should support changing arrays - 2", () => {234            const nextState = produce(235                baseState,236                s => {237                    s.anArray.splice(1, 1, "a", "b")238                },239                listener240            )241            expect(nextState).not.toBe(baseState)242            expect(nextState.anArray).not.toBe(baseState.anArray)243244            expect(enumerableOnly(nextState.anArray)).toEqual([245                3,246                "a",247                "b",248                {c: 3},249                1250            ])251        })252253        it("can delete array items", () => {254            const nextState = produce(255                baseState,256                s => {257                    s.anArray.length = 3258                },259                listener260            )261            expect(nextState).not.toBe(baseState)262            expect(nextState.anObject).toBe(baseState.anObject)263            expect(nextState.anArray).not.toBe(baseState.anArray)264            expect(nextState.anArray).toEqual([3, 2, {c: 3}])265        })266267        it("should support sorting arrays", () => {268            const nextState = produce(269                baseState,270                s => {271                    s.anArray[2].c = 4272                    s.anArray.sort()273                    s.anArray[3].c = 5274                },275                listener276            )277            expect(nextState).not.toBe(baseState)278            expect(nextState.anArray).not.toBe(baseState.anArray)279            expect(enumerableOnly(nextState.anArray)).toEqual([1, 2, 3, {c: 5}])280        })281282        it("should expose property descriptors", () => {283            const nextState = produce(284                [],285                s => {286                    expect(Object.getOwnPropertyDescriptor(s, 0)).toBe(287                        undefined288                    )289                    s.unshift("x")290                    expect(Object.getOwnPropertyDescriptor(s, 0)).toEqual({291                        configurable: true,292                        enumerable: true,293                        value: "x",294                        writable: true295                    })296                    expect(s.length).toBe(1)297                    expect(s[0] === "x").toBe(true)298                },299                listener300            )301            expect(nextState).toEqual(["x"])302            expect(Object.getOwnPropertyDescriptor(nextState, 0)).toEqual({303                configurable: !freeze,304                enumerable: true,305                value: "x",306                writable: !freeze307            })308        })309310        it("should support sorting arrays - 2", () => {311            const nextState = produce(312                baseState,313                s => {314                    s.anArray.unshift("x")315                    s.anArray[3].c = 4316                    s.anArray.sort()317                    s.anArray[3].c = 5318                    s.anArray.unshift("y")319                },320                listener321            )322            expect(nextState).not.toBe(baseState)323            expect(nextState.anArray).not.toBe(baseState.anArray)324            expect(enumerableOnly(nextState.anArray)).toEqual([325                "y",326                1,327                2,328                3,329                {c: 5},330                "x"331            ])332        })333334        it("should updating inside arrays", () => {335            const nextState = produce(336                baseState,337                s => {338                    s.anArray[2].test = true339                },340                listener341            )342            expect(nextState).not.toBe(baseState)343            expect(nextState.anArray).not.toBe(baseState.anArray)344            expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])345        })346347        it("can rename nested objects (no changes)", () => {348            const nextState = produce(349                baseState,350                s => {351                    const obj = s.anObject352                    delete s.anObject353                    s.renamed = obj354                },355                listener356            )357            expect(nextState).not.toBe(baseState)358            expect(nextState.anArray).toBe(baseState.anArray)359            expect(nextState.renamed.nested).toBe(baseState.anObject.nested)360            expect(enumerableOnly(nextState)).toEqual({361                anArray: [3, 2, {c: 3}, 1],362                aProp: "hi",363                renamed: {364                    nested: {365                        yummie: true366                    },367                    coffee: false368                }369            })370        })371372        // Very similar to the test before, but the reused object has one373        // property changed, one added, and one removed.374        it("can rename nested objects (with changes)", () => {375            const nextState = produce(376                baseState,377                s => {378                    const obj = s.anObject379                    delete s.anObject380381                    obj.coffee = true // change382                    obj.nested.yummy = true // add383                    delete obj.nested.yummie // delete384385                    s.renamed = obj386                },387                listener388            )389            expect(nextState).not.toBe(baseState)390            expect(nextState.anArray).toBe(baseState.anArray)391            expect(nextState.renamed.nested).not.toBe(baseState.anObject.nested)392            expect(enumerableOnly(nextState)).toEqual({393                anArray: [3, 2, {c: 3}, 1],394                aProp: "hi",395                renamed: {396                    nested: {397                        yummy: true398                    },399                    coffee: true400                }401            })402        })403404        it("can nest a draft in a new object (no changes)", () => {405            const nextState = produce(406                baseState,407                s => {408                    s.foo = {bar: s.anObject}409                    delete s.anObject410                },411                listener412            )413            expect(nextState).not.toBe(baseState)414            expect(nextState.foo.bar).toBe(baseState.anObject)415        })416417        it("can nest a draft in a new object (with changes)", () => {418            const nextState = produce(419                baseState,420                s => {421                    const obj = s.anObject422                    delete s.anObject423424                    obj.coffee = true // change425                    obj.nested.yummy = true // add426                    delete obj.nested.yummie // delete427428                    s.foo = {bar: obj}429                },430                listener431            )432            expect(nextState).not.toBe(baseState)433            expect(nextState.foo.bar).not.toBe(baseState.anObject)434            expect(nextState.foo).toEqual({435                bar: {436                    coffee: true,437                    nested: {yummy: true}438                }439            })440        })441442        it("should allow setting to undefined a defined draft property", () => {443            const nextState = produce(444                baseState,445                s => {446                    s.aProp = undefined447                },448                listener449            )450            expect(nextState).not.toBe(baseState)451            expect(baseState.aProp).toBe("hi")452            expect(nextState.aProp).toBe(undefined)453        })454455        // ES implementation does't protect against all outside modifications, just some..456        if (useProxies) {457            it("should revoke the proxy of the baseState after immer function is executed", () => {458                let proxy459                const nextState = produce(460                    baseState,461                    s => {462                        proxy = s463                        s.aProp = "hello"464                    },465                    listener466                )467                expect(nextState).not.toBe(baseState)468                expect(baseState.aProp).toBe("hi")469                expect(nextState.aProp).toBe("hello")470471                expect(() => {472                    proxy.aProp = "Hallo"473                }).toThrowError(/revoked/)474                expect(() => {475                    const aProp = proxy.aProp476                }).toThrowError(/revoked/)477478                expect(nextState).not.toBe(baseState)479                expect(baseState.aProp).toBe("hi")480                expect(nextState.aProp).toBe("hello")481            })482        }483484        it("should revoke the proxy of the baseState after immer function is executed - 2", () => {485            let proxy486            const nextState = produce(487                baseState,488                s => {489                    proxy = s.anObject490                },491                listener492            )493            expect(nextState).toBe(baseState)494            expect(() => {495                // In ES5 implemenation only protects existing props, but alas..496                proxy.coffee = "Hallo"497            }).toThrowError(/revoked/)498            expect(() => {499                const test = proxy.coffee500            }).toThrowError(/revoked/)501        })502503        it("should reflect all changes made in the draft immediately", () => {504            produce(505                baseState,506                draft => {507                    draft.anArray[0] = 5508                    draft.anArray.unshift("test")509                    // sliced here; jest will also compare non-enumerable keys, which would include the immer Symbols510                    expect(draft.anArray.slice()).toMatchObject([511                        "test",512                        5,513                        2,514                        {c: 3},515                        1516                    ])517                    draft.stuffz = "coffee"518                    expect(draft.stuffz).toBe("coffee")519                },520                listener521            )522        })523524        it("should be able to get property descriptors from objects", () => {525            produce(526                {a: 1},527                draft => {528                    expect("a" in draft).toBe(true)529                    expect("b" in draft).toBe(false)530                    expect(531                        Reflect.ownKeys(draft).filter(532                            x => typeof x === "string"533                        )534                    ).toEqual(["a"])535536                    expect(537                        Object.getOwnPropertyDescriptor(draft, "a")538                    ).toMatchObject({539                        configurable: true,540                        enumerable: true541                    })542                    draft.a = 2543                    expect(544                        Object.getOwnPropertyDescriptor(draft, "a")545                    ).toMatchObject({546                        configurable: true,547                        enumerable: true548                    })549                    expect(550                        Object.getOwnPropertyDescriptor(draft, "b")551                    ).toBeUndefined()552                    draft.b = 2553                    expect(554                        Object.getOwnPropertyDescriptor(draft, "b")555                    ).toMatchObject({556                        configurable: true,557                        enumerable: true558                    })559                    expect("a" in draft).toBe(true)560                    expect("b" in draft).toBe(true)561                    expect(562                        Reflect.ownKeys(draft).filter(563                            x => typeof x === "string"564                        )565                    ).toEqual(["a", "b"])566                },567                listener568            )569        })570571        it("should be able to get property descriptors from arrays", () => {572            produce(573                [1],574                draft => {575                    expect(0 in draft).toBe(true)576                    expect(1 in draft).toBe(false)577                    expect("0" in draft).toBe(true)578                    expect("1" in draft).toBe(false)579                    expect(length in draft).toBe(true)580                    expect(581                        Reflect.ownKeys(draft).filter(582                            x => typeof x === "string"583                        )584                    ).toEqual(["0", "length"])585586                    expect(587                        Object.getOwnPropertyDescriptor(draft, "length")588                    ).toMatchObject({589                        configurable: false,590                        enumerable: false591                    })592                    draft[0] = 2593                    expect(594                        Object.getOwnPropertyDescriptor(draft, 0)595                    ).toMatchObject({596                        configurable: true,597                        enumerable: true598                    })599                    expect(600                        Object.getOwnPropertyDescriptor(draft, 0)601                    ).toMatchObject({602                        configurable: true,603                        enumerable: true604                    })605                    expect(606                        Object.getOwnPropertyDescriptor(draft, 1)607                    ).toBeUndefined()608                    draft[1] = 2609                    expect(610                        Object.getOwnPropertyDescriptor(draft, 1)611                    ).toMatchObject({612                        configurable: true,613                        enumerable: true614                    })615                    expect(616                        Reflect.ownKeys(draft).filter(617                            x => typeof x === "string"618                        )619                    ).toEqual(["0", "1", "length"])620                },621                listener622            )623        })624625        if (useProxies === true) {626            it("should not be possible to set property descriptors", () => {627                expect(() => {628                    produce(629                        {},630                        draft => {631                            Object.defineProperty(draft, "xx", {632                                enumerable: true,633                                writeable: true,634                                value: 2635                            })636                        },637                        listener638                    )639                }).toThrowError(/not support/)640            })641642            it("should not be possible to add properties to arrays", () => {643                expect(() => {644                    produce([], d => {645                        d.x = 3646                    })647                }).toThrow(648                    "Immer does not support setting non-numeric properties on arrays"649                )650            })651652            it("should not be possible to remove properties from arrays", () => {653                expect(() => {654                    const base = []655                    base.x = 7656                    produce(base, d => {657                        delete d.x658                    })659                }).toThrow(660                    "Immer does not support deleting properties from arrays"661                )662            })663        }664665        it("non-numeric array properties will be lost", () => {666            const base = []667            base.x = 7668            const next = produce(base, d => {669                d.push(3)670            })671            expect(next.x).toBe(undefined)672        })673674        it("should not throw error, see #53 - 1", () => {675            const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}676            const result = produce(677                base,678                draft => {679                    draft.arr = draft.arr.filter(item => item.count > 2)680                },681                listener682            )683            expect(result.arr[0].count).toEqual(3)684            expect(result).toEqual({685                arr: [{count: 3}]686            })687            expect(result.arr[0]).toBe(base.arr[2])688        })689690        it("should not throw error, see #53 - 2", () => {691            const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}692            const result = produce(693                base,694                draft => {695                    draft.newArr = draft.arr.filter(item => item.count > 2)696                },697                listener698            )699            expect(result.newArr[0].count).toEqual(3)700            expect(result.arr).toBe(base.arr)701            expect(result).toEqual({702                arr: [703                    {704                        count: 1705                    },706                    {707                        count: 2708                    },709                    {710                        count: 3711                    }712                ],713                newArr: [714                    {715                        count: 3716                    }717                ]718            })719            expect(result.newArr[0]).toBe(base.arr[2])720            expect(result.arr[2]).toBe(base.arr[2])721        })722723        it("should not throw error, see #53 - 3", () => {724            const base = {arr: [{count: 1}, {count: 2}, {count: 3}]}725            const result = produce(726                base,727                draft => {728                    draft.newArr = draft.arr.filter(item => item.count > 2)729                    delete draft.arr730                },731                listener732            )733            expect(result.newArr[0].count).toEqual(3)734            expect(result).toEqual({735                newArr: [{count: 3}]736            })737            expect(result.newArr[0]).toBe(base.arr[2])738        })739740        it("should not throw error, see #53 - 4", () => {741            const base = {bear: {age: 10}}742            const result = produce(743                base,744                draft => {745                    draft.bear.legs = 4746                    draft.room = {elephant: {kiddo: draft.bear}}747                },748                listener749            )750            expect(result).toEqual({751                bear: {age: 10, legs: 4},752                room: {elephant: {kiddo: {age: 10, legs: 4}}}753            })754755            const result2 = produce(result, draft => {756                draft.bear.age = 11757                draft.room.elephant.kiddo.legs = 5758            })759            expect(result2).toEqual({760                bear: {age: 11, legs: 4},761                room: {elephant: {kiddo: {age: 10, legs: 5}}}762            })763        })764765        it("should not throw error #78", () => {766            const base = {767                arr: [768                    {769                        id: "100",770                        arr: [{id: "1", no: 1}, {id: "2", no: 2}]771                    },772                    {id: "3", no: 3}773                ]774            }775            const result = produce(base, draft => {776                const base = draft.arr[0]777                draft.arr = draft.arr.slice(0, 1)778                const newArr = {779                    id: "101",780                    arr: [base, {id: "3"}]781                }782                draft.arr.splice(0, 1, newArr)783                draft.arr[0].arr[1].no = 3784            })785            expect(result).toEqual({786                arr: [787                    {788                        id: "101",789                        arr: [790                            {791                                id: "100",792                                arr: [{id: "1", no: 1}, {id: "2", no: 2}]793                            },794                            {id: "3", no: 3}795                        ]796                    }797                ]798            })799        })800801        it("should not throw error #78 - 2", () => {802            const base = {803                arr: [{count: 1}, {count: 2}]804            }805            const result = produce(base, draft => {806                draft.arr = [draft.arr[1]]807                draft.arr[0].count = 1808            })809            expect(result).toEqual({810                arr: [{count: 1}]811            })812        })813814        it("should handle constructor correctly", () => {815            const base = {816                arr: new Array(),817                obj: new Object()818            }819            const result = produce(base, draft => {820                draft.arrConstructed = draft.arr.constructor(1)821                draft.objConstructed = draft.obj.constructor(1)822            })823            expect(result.arrConstructed).toEqual(new Array().constructor(1))824            expect(result.objConstructed).toEqual(new Object().constructor(1))825        })826827        it("should handle dates correctly", () => {828            const data = {date: new Date()}829            const next = produce(data, draft => {830                draft.x = true831            })832            expect(next).toEqual({x: true, date: data.date})833            expect(next.date).toBe(data.date)834            const next2 = produce(next, draft => {835                draft.date.setYear(2015)836            })837            // This still holds; because produce won't proxy Date objects838            // and the original is actually modified!839            expect(next2).toEqual({x: true, date: data.date})840            expect(next2.date).toBe(next.date)841            expect(next2.date).toBe(data.date)842            expect(next2).toBe(next)843        })844845        it("should handle equality correctly - 1", () => {846            const base = {847                y: 3 / 0,848                z: NaN849            }850            const next = produce(base, draft => {851                draft.y = 4 / 0852                draft.z = NaN853            })854            expect(next).toEqual(base)855            expect(next).toBe(base)856        })857858        it("should handle equality correctly - 2", () => {859            const base = {860                x: -0861            }862            const next = produce(base, draft => {863                draft.x = +1864            })865            expect(next).not.toEqual(base)866            expect(next).not.toBe(base)867        })868869        describe("nested immer.produce() call", () => {870            describe("with non-draft object", () => {871                // This test ensures the global state used to manage proxies is872                // never left in a corrupted state by a nested `produce` call.873                it("never affects its parent producer implicitly", () => {874                    const bear = {paw: {honey: true}}875                    const next = produce(876                        bear,877                        draft => {878                            const paw2 = produce(bear.paw, draft => {879                                draft.honey = false880                            })881                            expect(paw2.honey).toBe(false)882                            expect(draft.paw.honey).toBe(true) // effects should not be visible outside883                        },884                        listener885                    )886                    expect(next.paw.honey).toBe(true)887                    expect(next).toBe(bear)888                })889890                it("returns a normal object", () => {891                    const bear = {paw: {honey: true}}892                    const next = produce(893                        bear,894                        draft => {895                            const paw2 = produce(bear.paw, draft => {896                                draft.honey = false897                            })898                            expect(paw2.honey).toBe(false)899                            expect(draft.paw.honey).toBe(true)900                            draft.paw = paw2901                            expect(draft.paw.honey).toBe(false)902                        },903                        listener904                    )905                    expect(next.paw.honey).toBe(false)906                    expect(next).not.toBe(bear)907                })908            })909910            describe("with a draft object", () => {911                it("always reuses the draft", () => {912                    const bear = {paw: {honey: true}}913                    const next = produce(914                        bear,915                        bear => {916                            const paw2 = produce(bear.paw, paw => {917                                expect(paw).toBe(bear.paw)918                                paw.honey = false919                            })920                            expect(paw2).toBe(bear.paw)921                            expect(paw2.honey).toBe(false)922                            expect(bear.paw.honey).toBe(false)923                        },924                        listener925                    )926                    expect(next.paw.honey).toBe(false)927                    expect(next).not.toBe(bear)928                })929            })930        })931932        it("should not try to change immutable data, see #66", () => {933            const user = require("./test-data")934935            const base = {}936            const next = produce(937                base,938                draft => {939                    draft.user = user940                },941                listener942            )943            expect(next.user).toBe(user)944            expect(next).not.toBe(base)945            expect(next.user).toEqual(user)946        })947948        it("should not try to change immutable data, see #66 - 2", () => {949            const user = deepFreeze(cloneDeep(require("./test-data")))950951            const base = {}952            const next = produce(953                base,954                draft => {955                    draft.user = user956                },957                listener958            )959            expect(next.user).toBe(user)960            expect(next).not.toBe(base)961            expect(next.user).toEqual(user)962        })963964        it("should structurally share identical objects in the tree", () => {965            const base = {bear: {legs: 4}, eagle: {legs: 3}}966            const next = produce(967                base,968                draft => {969                    const animal = draft.bear970                    animal.legs = animal.legs + 1971                    draft.bear = animal972                    draft.eagle = animal973                    draft.cow = animal974                    draft.kiddo = animal975                },976                listener977            )978            expect(next).toEqual({979                bear: {legs: 5},980                eagle: {legs: 5},981                cow: {legs: 5},982                kiddo: {legs: 5}983            })984            expect(next.bear).toBe(next.cow)985            expect(next.kiddo).toBe(next.cow)986        })987988        if (useProxies)989            it("should not allow changing prototype", () => {990                produce(991                    {},992                    draft => {993                        expect(() =>994                            Object.setPrototypeOf(draft, Array)995                        ).toThrow(/does not support `setPrototype/)996                    },997                    listener998                )999            })10001001        it("'in' should work", () => {1002            produce(1003                createBaseState(),1004                draft => {1005                    expect("anArray" in draft).toBe(true)1006                    expect(Reflect.has(draft, "anArray")).toBe(true)10071008                    expect("bla" in draft).toBe(false)1009                    expect(Reflect.has(draft, "bla")).toBe(false)10101011                    expect(0 in draft.anArray).toBe(true)1012                    expect("0" in draft.anArray).toBe(true)1013                    expect(Reflect.has(draft.anArray, 0)).toBe(true)1014                    expect(Reflect.has(draft.anArray, "0")).toBe(true)10151016                    expect(17 in draft.anArray).toBe(false)1017                    expect("17" in draft.anArray).toBe(false)1018                    expect(Reflect.has(draft.anArray, 17)).toBe(false)1019                    expect(Reflect.has(draft.anArray, "17")).toBe(false)1020                },1021                listener1022            )1023        })10241025        it("'this' should work - 1", () => {1026            const base = {x: 3}1027            const next1 = produce(1028                base,1029                function() {1030                    this.x = 41031                },1032                listener1033            )1034            expect(next1).not.toBe(base)1035            expect(next1.x).toBe(4)1036        })10371038        it("'this' should work - 1", () => {1039            const base = {x: 3}1040            const incrementor = produce(function() {1041                this.x = 41042            })1043            const next1 = incrementor(base)1044            expect(next1).not.toBe(base)1045            expect(next1.x).toBe(4)1046        })10471048        it("issue #89", () => {1049            const state = {1050                users: {1051                    existingID: {1052                        loading: false,1053                        value: "val"1054                    }1055                }1056            }1057            const nextState = produce(1058                state,1059                draft => {1060                    draft.users.existingID = {1061                        ...draft.users.existingID,1062                        loading: true1063                    }1064                },1065                listener1066            )1067            expect(nextState).toEqual({1068                users: {1069                    existingID: {1070                        loading: true,1071                        value: "val"1072                    }1073                }1074            })1075        })10761077        it("processes with lodash.set", () => {1078            const base = [{id: 1, a: 1}]1079            const result = produce(1080                base,1081                draft => {1082                    lodash.set(draft, "[0].a", 2)1083                },1084                listener1085            )1086            expect(base[0].a).toEqual(1)1087            expect(result[0].a).toEqual(2)1088        })10891090        it("processes with lodash.find", () => {1091            const base = [{id: 1, a: 1}]1092            const result = produce(1093                base,1094                draft => {1095                    const obj1 = lodash.find(draft, {id: 1})1096                    lodash.set(obj1, "a", 2)1097                },1098                listener1099            )1100            expect(base[0].a).toEqual(1)1101            expect(result[0].a).toEqual(2)1102        })11031104        it("can produce from no state", () => {1105            expect(1106                produce(1107                    3,1108                    draft => {1109                        expect(draft).toBe(3)1110                        return 51111                    },1112                    listener1113                )1114            ).toBe(5)1115        })11161117        it("can return something new ", () => {1118            const base = {x: 3}1119            const res = produce(1120                base,1121                draft => {1122                    return {x: draft.x + 1}1123                },1124                listener1125            )1126            expect(res).not.toBe(base)1127            expect(res).toEqual({x: 4})1128        })11291130        it("can return the draft new ", () => {1131            const base = {x: 3}1132            const res = produce(1133                base,1134                draft => {1135                    draft.x = 41136                    return draft1137                },1138                listener1139            )1140            expect(res).not.toBe(base)1141            expect(res).toEqual({x: 4})1142        })11431144        it("should throw if modifying the draft and returning something new", () => {1145            const base = {x: 3}1146            expect(() => {1147                produce(1148                    base,1149                    draft => {1150                        draft.x = 41151                        return {x: 5}1152                    },1153                    listener1154                )1155            }).toThrow(/An immer producer returned a new value/)1156        })11571158        it("should fix #116", () => {1159            const nextState = produce(1160                [1, 2, 3],1161                s => {1162                    s.pop()1163                    s.push(100)1164                },1165                listener1166            )1167            expect(nextState).toEqual([1, 2, 100])1168        })11691170        it("should fix #117", () => {1171            const reducer = (state, action) =>1172                produce(1173                    state,1174                    draft => {1175                        switch (action.type) {1176                            case "SET_STARTING_DOTS":1177                                return draft.availableStartingDots.map(a => a)1178                            default:1179                                break1180                        }1181                    },1182                    listener1183                )1184            const base = {1185                availableStartingDots: [1186                    {dots: 4, count: 1},1187                    {dots: 3, count: 2},1188                    {dots: 2, count: 3},1189                    {dots: 1, count: 4}1190                ]1191            }1192            const next = reducer(base, {type: "SET_STARTING_DOTS"})1193            expect(next).toEqual(base.availableStartingDots)1194            expect(next).not.toBe(base.availableStartingDots)1195        })11961197        it("should fix #117 - 2", () => {1198            const reducer = (state, action) =>1199                produce(1200                    state,1201                    draft => {1202                        switch (action.type) {1203                            case "SET_STARTING_DOTS":1204                                return {1205                                    dots: draft.availableStartingDots.map(1206                                        a => a1207                                    )1208                                }1209                            default:1210                                break1211                        }1212                    },1213                    listener1214                )1215            const base = {1216                availableStartingDots: [1217                    {dots: 4, count: 1},1218                    {dots: 3, count: 2},1219                    {dots: 2, count: 3},1220                    {dots: 1, count: 4}1221                ]1222            }1223            const next = reducer(base, {type: "SET_STARTING_DOTS"})1224            expect(next).toEqual({dots: base.availableStartingDots})1225        })12261227        it("should return an unmodified primitive baseState (#148)", () => {1228            const baseState = "some string"1229            const nextState = produce(1230                baseState,1231                () => {1232                    /* no modification  */1233                },1234                listener1235            )1236            expect(nextState).toBe(baseState)1237        })12381239        it("should return an unmodified null baseState (#148)", () => {1240            const baseState = null1241            const nextState = produce(1242                baseState,1243                () => {1244                    /* no modification  */1245                },1246                listener1247            )1248            expect(nextState).toBe(baseState)1249        })12501251        it("should not detect noop assignments - 0", () => {1252            const baseState = {x: {y: 3}}1253            const nextState = produce(1254                baseState,1255                d => {1256                    const a = d.x1257                    d.x = a1258                },1259                listener1260            )1261            expect(nextState).toBe(baseState)1262        })12631264        it("should not detect noop assignments - 1", () => {1265            const baseState = {x: {y: 3}}1266            const nextState = produce(1267                baseState,1268                d => {1269                    const a = d.x1270                    d.x = 41271                    d.x = a1272                },1273                listener1274            )1275            // Ideally, this should actually be the same instances1276            // but this would be pretty expensive to detect,1277            // so we don't atm1278            expect(nextState).not.toBe(baseState)1279        })12801281        it("should not detect noop assignments - 2", () => {1282            const baseState = {x: {y: 3}}1283            const nextState = produce(1284                baseState,1285                d => {1286                    const a = d.x1287                    const stuff = a.y + 31288                    d.x = 41289                    d.x = a1290                },1291                listener1292            )1293            // Ideally, this should actually be the same instances1294            // but this would be pretty expensive to detect,1295            // so we don't atm1296            expect(nextState).not.toBe(baseState)1297        })12981299        it("should not detect noop assignments - 3", () => {1300            const baseState = {x: 3}1301            const nextState = produce(1302                baseState,1303                d => {1304                    d.x = 31305                },1306                listener1307            )1308            expect(nextState).toBe(baseState)1309        })13101311        it("should not detect noop assignments - 4", () => {1312            const baseState = {x: 3}1313            const nextState = produce(1314                baseState,1315                d => {1316                    d.x = 41317                    d.x = 31318                },1319                listener1320            )1321            // Ideally, this should actually be the same instances1322            // but this would be pretty expensive to detect,1323            // so we don't atm1324            expect(nextState).not.toBe(baseState)1325        })13261327        it("immer should have no dependencies", () => {1328            expect(require("../package.json").dependencies).toEqual(undefined)1329        })13301331        it("#174", () => {1332            const nextState = produce([1, 2, 3], s => {1333                s.pop()1334                s.push(100)1335            })1336            expect(nextState).toEqual([1, 2, 100])1337        })13381339        it("#195 should be able to find items", () => {1340            const state = {1341                items: [1342                    {1343                        id: 0,1344                        task: "drink milk"1345                    },1346                    {id: 1, task: "eat cookie"}1347                ]1348            }1349            produce(state, draft => {1350                expect(draft.items.find(({id}) => id === 1).task).toBe(1351                    "eat cookie"1352                )1353            })1354        })13551356        it("allows a function as the base state", () => {1357            let fn = () => {}1358            expect(1359                produce(fn, draft => {1360                    expect(fn).toBe(draft)1361                })1362            ).toBe(fn)1363        })13641365        it("cannot return and produce undefined!", () => {1366            const base = 31367            expect(produce(base, () => 4)).toBe(4)1368            expect(produce(base, () => null)).toBe(null)1369            expect(produce(base, () => undefined)).toBe(3)1370            expect(produce(base, () => {})).toBe(3)1371            expect(produce(base, () => nothing)).toBe(undefined)13721373            expect(produce({}, () => undefined)).toEqual({})1374            expect(produce({}, () => nothing)).toBe(undefined)1375            expect(produce(3, () => nothing)).toBe(undefined)13761377            expect(produce(() => undefined)({})).toEqual({})1378            expect(produce(() => nothing)({})).toBe(undefined)1379            expect(produce(() => nothing)(3)).toBe(undefined)1380        })13811382        // TODO: use fuzz testing1383        {1384            class Foo {}1385            const primitives = {1386                "falsy number": 0,1387                "truthy number": 1,1388                "negative number": -1,1389                infinity: 1 / 0,1390                true: true,1391                false: false,1392                "empty string": "",1393                "truthy string": "1",1394                null: null,1395                undefined: undefined,13961397                /**1398                 * These objects are treated as primitives because Immer1399                 * chooses not to make drafts for them.1400                 */1401                "regexp object": /.+/g,1402                "boxed number": new Number(0),1403                "boxed string": new String(""),1404                "boxed boolean": new Boolean(),1405                "date object": new Date(),1406                "class instance": new Foo()1407            }1408            for (const name in primitives) {1409                describe("base state type - " + name, () => {1410                    const value = primitives[name]1411                    it("does not create a draft", () => {1412                        produce(value, draft => {1413                            expect(draft).toBe(value)1414                        })1415                    })1416                    it("returns the same value when the producer returns undefined", () => {1417                        expect(produce(value, () => {})).toBe(value)1418                    })1419                    if (value && typeof value == "object") {1420                        it("does not return a copy when the producer makes changes", () => {1421                            expect(1422                                produce(value, draft => {1423                                    draft.foo = true1424                                })1425                            ).toBe(value)1426                        })1427                    }1428                })1429            }1430            const objects = {1431                "empty object": {},1432                "plain object": {a: 1, b: {c: 1}},1433                "frozen object": Object.freeze({}),1434                "null-prototype object": Object.create(null),1435                "frozen null-prototype object": Object.freeze(1436                    Object.create(null)1437                ),1438                "empty array": [],1439                "plain array": [1, [2, [3, []]]],1440                "frozen array": Object.freeze([])1441            }1442            for (const name in objects) {1443                describe("base state type - " + name, () => {1444                    const value = objects[name]1445                    it("creates a draft", () => {1446                        produce(value, draft => {1447                            expect(draft).not.toBe(value)1448                            expect(enumerableOnly(draft)).toEqual(value)1449                        })1450                    })1451                    it("returns the same value when the producer does nothing", () => {1452                        expect(produce(value, () => {})).toBe(value)1453                    })1454                    it("returns a copy when changes are made", () => {1455                        const random = Math.random()1456                        const result = produce(value, draft => {1457                            draft[0] = random1458                        })1459                        expect(result).not.toBe(value)1460                        expect(result.constructor).toBe(value.constructor)1461                        expect(result[0]).toBe(random)1462                    })1463                })1464            }1465        }14661467        afterEach(() => {1468            expect(baseState).toBe(origBaseState)1469            expect(baseState).toEqual(createBaseState())1470        })14711472        function createBaseState() {1473            const data = {1474                anArray: [3, 2, {c: 3}, 1],1475                aProp: "hi",1476                anObject: {1477                    nested: {1478                        yummie: true1479                    },1480                    coffee: false1481                }1482            }1483            return freeze ? deepFreeze(data) : data1484        }1485    })14861487    describe(`isDraft - ${name}`, () => {1488        beforeAll(() => {1489            setAutoFreeze(freeze)1490            setUseProxies(useProxies)1491        })14921493        it("returns true for object drafts", () => {1494            produce({}, state => {1495                expect(isDraft(state)).toBeTruthy()1496            })1497        })1498        it("returns true for array drafts", () => {1499            produce([], state => {1500                expect(isDraft(state)).toBeTruthy()1501            })1502        })1503        it("returns true for objects nested in object drafts", () => {1504            produce({a: {b: {}}}, state => {1505                expect(isDraft(state.a)).toBeTruthy()1506                expect(isDraft(state.a.b)).toBeTruthy()1507            })1508        })1509        it("returns false for new objects added to a draft", () => {1510            produce({}, state => {1511                state.a = {}1512                expect(isDraft(state.a)).toBeFalsy()1513            })1514        })1515        it("returns false for objects returned by the producer", () => {1516            const object = produce(null, Object.create)1517            expect(isDraft(object)).toBeFalsy()1518        })1519        it("returns false for arrays returned by the producer", () => {1520            const array = produce(null, _ => [])1521            expect(isDraft(array)).toBeFalsy()1522        })1523        it("returns false for object drafts returned by the producer", () => {1524            const object = produce({}, state => state)1525            expect(isDraft(object)).toBeFalsy()1526        })1527        it("returns false for array drafts returned by the producer", () => {1528            const array = produce([], state => state)1529            expect(isDraft(array)).toBeFalsy()1530        })1531    })1532}15331534function enumerableOnly(x) {1535    // this can be done better...1536    return JSON.parse(JSON.stringify(x))1537}