Skip to content
Myr

base.js

This file

Path

__tests__/base.js

2,459 lines · 61.8 KiB · JavaScript

Last changed by

chore: Migrate test setup to Vitest (#1162)Mark Eriksonbefore adoption4b8bcc5

History of this file

Take it

1"use strict"2import {vi} from "vitest"3import {4	Immer,5	nothing,6	original,7	isDraft,8	immerable,9	enablePatches,10	enableMapSet11} from "../src/immer"12import {each, shallowCopy, DRAFT_STATE} from "../src/internal"13import deepFreeze from "deep-freeze"14import * as lodash from "lodash"1516enablePatches()17enableMapSet()1819vi.setConfig({20	testTimeout: 100021})2223const isProd = process.env.NODE_ENV === "production"2425test("immer should have no dependencies", () => {26	expect(require("../package.json").dependencies).toBeUndefined()27})2829for (const autoFreeze of [true, false]) {30	for (const useStrictShallowCopy of [true, false]) {31		for (const useListener of [true, false]) {32			const name = `${autoFreeze ? "auto-freeze=true" : "auto-freeze=false"}:${33				useStrictShallowCopy ? "shallow-copy=true" : "shallow-copy=false"34			}:${useListener ? "use-listener=true" : "use-listener=false"}`35			runBaseTest(name, autoFreeze, useStrictShallowCopy, useListener)36		}37	}38}3940class Foo {}4142function runBaseTest(name, autoFreeze, useStrictShallowCopy, useListener) {43	const listener = useListener ? function() {} : undefined44	const {produce, produceWithPatches} = createPatchedImmer({45		autoFreeze,46		useStrictShallowCopy47	})4849	// When `useListener` is true, append a function to the arguments of every50	// uncurried `produce` call in every test. This makes tests easier to read.51	function createPatchedImmer(options) {52		const immer = new Immer(options)5354		const {produce} = immer55		immer.produce = function(...args) {56			return typeof args[1] === "function" && args.length < 357				? produce(...args, listener)58				: produce(...args)59		}6061		return immer62	}6364	describe(`base functionality - ${name}`, () => {65		let baseState66		let origBaseState6768		beforeEach(() => {69			origBaseState = baseState = createBaseState()70		})7172		it("returns the original state when no changes are made", () => {73			const nextState = produce(baseState, s => {74				expect(s.aProp).toBe("hi")75				expect(s.anObject.nested).toMatchObject({yummie: true})76			})77			expect(nextState).toBe(baseState)78		})7980		it("does structural sharing", () => {81			const random = Math.random()82			const nextState = produce(baseState, s => {83				s.aProp = random84			})85			expect(nextState).not.toBe(baseState)86			expect(nextState.aProp).toBe(random)87			expect(nextState.nested).toBe(baseState.nested)88		})8990		it("deep change bubbles up", () => {91			const nextState = produce(baseState, s => {92				s.anObject.nested.yummie = false93			})94			expect(nextState).not.toBe(baseState)95			expect(nextState.anObject).not.toBe(baseState.anObject)96			expect(baseState.anObject.nested.yummie).toBe(true)97			expect(nextState.anObject.nested.yummie).toBe(false)98			expect(nextState.anArray).toBe(baseState.anArray)99		})100101		it("can add props", () => {102			const nextState = produce(baseState, s => {103				s.anObject.cookie = {tasty: true}104			})105			expect(nextState).not.toBe(baseState)106			expect(nextState.anObject).not.toBe(baseState.anObject)107			expect(nextState.anObject.nested).toBe(baseState.anObject.nested)108			expect(nextState.anObject.cookie).toEqual({tasty: true})109		})110111		it("can delete props", () => {112			const nextState = produce(baseState, s => {113				delete s.anObject.nested114				delete s.nonexisting115			})116			expect(nextState).not.toBe(baseState)117			expect(nextState.anObject).not.toBe(baseState.anObject)118			expect(nextState.anObject.nested).toBe(undefined)119		})120121		it("can delete props - 2", () => {122			const nextState = produce(baseState, s => {123				delete s.nonexisting124			})125			expect(nextState).toBe(baseState)126		})127128		// Found by: https://github.com/mweststrate/immer/pull/267129		it("can delete props added in the producer", () => {130			const nextState = produce(baseState, s => {131				s.anObject.test = true132				delete s.anObject.test133			})134			expect(nextState).not.toBe(baseState)135			expect(nextState).toEqual(baseState)136		})137138		// Found by: https://github.com/mweststrate/immer/issues/328139		it("can set a property that was just deleted", () => {140			const baseState = {a: 1}141			const nextState = produce(baseState, s => {142				delete s.a143				s.a = 2144			})145			expect(nextState.a).toBe(2)146		})147148		it("can set a property to its original value after deleting it", () => {149			const baseState = {a: {b: 1}}150			const nextState = produce(baseState, s => {151				const a = s.a152				delete s.a153				s.a = a154			})155			expect(nextState).not.toBe(baseState)156			expect(nextState).toEqual(baseState)157		})158159		it("can get property descriptors", () => {160			const getDescriptor = Object.getOwnPropertyDescriptor161			const baseState = deepFreeze([{a: 1}])162			produce(baseState, arr => {163				const obj = arr[0]164				const desc = {165					configurable: true,166					enumerable: true,167					writable: true168				}169170				// Known property171				expect(getDescriptor(obj, "a")).toMatchObject(desc)172				expect(getDescriptor(arr, 0)).toMatchObject(desc)173174				// Deleted property175				delete obj.a176				arr.pop()177				expect(getDescriptor(obj, "a")).toBeUndefined()178				expect(getDescriptor(arr, 0)).toBeUndefined()179180				// Unknown property181				expect(getDescriptor(obj, "b")).toBeUndefined()182				expect(getDescriptor(arr, 100)).toBeUndefined()183184				// Added property185				obj.b = 2186				arr[100] = 1187				expect(getDescriptor(obj, "b")).toBeDefined()188				expect(getDescriptor(arr, 100)).toBeDefined()189			})190		})191192		describe("array drafts", () => {193			it("supports Array.isArray()", () => {194				const nextState = produce(baseState, s => {195					expect(Array.isArray(s.anArray)).toBeTruthy()196					s.anArray.push(1)197				})198				expect(Array.isArray(nextState.anArray)).toBeTruthy()199			})200201			it("supports index access", () => {202				const value = baseState.anArray[0]203				const nextState = produce(baseState, s => {204					expect(s.anArray[0]).toBe(value)205				})206				expect(nextState).toBe(baseState)207			})208209			it("supports iteration", () => {210				const base = [211					{id: 1, a: 1},212					{id: 2, a: 1}213				]214				const findById = (collection, id) => {215					for (const item of collection) {216						if (item.id === id) return item217					}218					return null219				}220				const result = produce(base, draft => {221					const obj1 = findById(draft, 1)222					const obj2 = findById(draft, 2)223					obj1.a = 2224					obj2.a = 2225				})226				expect(result[0].a).toEqual(2)227				expect(result[1].a).toEqual(2)228			})229230			it("can assign an index via bracket notation", () => {231				const nextState = produce(baseState, s => {232					s.anArray[3] = true233				})234				expect(nextState).not.toBe(baseState)235				expect(nextState.anArray).not.toBe(baseState.anArray)236				expect(nextState.anArray[3]).toEqual(true)237			})238239			it("can use splice() to both add and remove items", () => {240				const nextState = produce(baseState, s => {241					s.anArray.splice(1, 1, "a", "b")242				})243				expect(nextState.anArray).not.toBe(baseState.anArray)244				expect(nextState.anArray[1]).toBe("a")245				expect(nextState.anArray[2]).toBe("b")246			})247248			it("can truncate via the length property", () => {249				const baseLength = baseState.anArray.length250				const nextState = produce(baseState, s => {251					s.anArray.length = baseLength - 1252				})253				expect(nextState.anArray).not.toBe(baseState.anArray)254				expect(nextState.anArray.length).toBe(baseLength - 1)255			})256257			it("can extend via the length property", () => {258				const baseLength = baseState.anArray.length259				const nextState = produce(baseState, s => {260					s.anArray.length = baseLength + 1261				})262				expect(nextState.anArray).not.toBe(baseState.anArray)263				expect(nextState.anArray.length).toBe(baseLength + 1)264			})265266			// Reported here: https://github.com/mweststrate/immer/issues/116267			it("can pop then push", () => {268				const nextState = produce([1, 2, 3], s => {269					s.pop()270					s.push(100)271				})272				expect(nextState).toEqual([1, 2, 100])273			})274275			it("can be sorted", () => {276				const baseState = [3, 1, 2]277				const nextState = produce(baseState, s => {278					s.sort()279				})280				expect(nextState).not.toBe(baseState)281				expect(nextState).toEqual([1, 2, 3])282			})283284			it("supports modifying nested objects", () => {285				const baseState = [{a: 1}, {}]286				const nextState = produce(baseState, s => {287					s[0].a++288					s[1].a = 0289				})290				expect(nextState).not.toBe(baseState)291				expect(nextState[0].a).toBe(2)292				expect(nextState[1].a).toBe(0)293			})294295			it("never preserves non-numeric properties", () => {296				const baseState = []297				baseState.x = 7298				const nextState = produce(baseState, s => {299					s.push(3)300				})301				expect("x" in nextState).toBeFalsy()302			})303304			if (!global.USES_BUILD) {305				it("throws when a non-numeric property is added", () => {306					expect(() => {307						produce([], d => {308							d.x = 3309						})310					}).toThrowErrorMatchingSnapshot()311				})312313				it("throws when a non-numeric property is deleted", () => {314					expect(() => {315						const baseState = []316						baseState.x = 7317						produce(baseState, d => {318							delete d.x319						})320					}).toThrowErrorMatchingSnapshot()321				})322			}323		})324325		describe("map drafts", () => {326			it("supports key access", () => {327				const value = baseState.aMap.get("jedi")328				const nextState = produce(baseState, s => {329					expect(s.aMap.get("jedi")).toEqual(value)330				})331				expect(nextState).toBe(baseState)332			})333334			it("supports key access for non-primitive keys", () => {335				const key = {prop: "val"}336				const base = new Map([[key, {id: 1, a: 1}]])337				const value = base.get(key)338				const nextState = produce(base, s => {339					expect(s.get(key)).toEqual(value)340				})341				expect(nextState).toBe(base)342			})343344			it("supports iteration", () => {345				const base = new Map([346					["first", {id: 1, a: 1}],347					["second", {id: 2, a: 1}]348				])349				const findById = (map, id) => {350					for (const [, item] of map) {351						if (item.id === id) return item352					}353					return null354				}355				const result = produce(base, draft => {356					const obj1 = findById(draft, 1)357					const obj2 = findById(draft, 2)358					obj1.a = 2359					obj2.a = 2360				})361				expect(result).not.toBe(base)362				expect(result.get("first").a).toEqual(2)363				expect(result.get("second").a).toEqual(2)364			})365366			it("supports 'entries'", () => {367				const base = new Map([368					["first", {id: 1, a: 1}],369					["second", {id: 2, a: 1}]370				])371				const findById = (map, id) => {372					for (const [, item] of map.entries()) {373						if (item.id === id) return item374					}375					return null376				}377				const result = produce(base, draft => {378					const obj1 = findById(draft, 1)379					const obj2 = findById(draft, 2)380					obj1.a = 2381					obj2.a = 2382				})383				expect(result).not.toBe(base)384				expect(result.get("first").a).toEqual(2)385				expect(result.get("second").a).toEqual(2)386			})387388			it("supports 'values'", () => {389				const base = new Map([390					["first", {id: 1, a: 1}],391					["second", {id: 2, a: 1}]392				])393				const findById = (map, id) => {394					for (const item of map.values()) {395						if (item.id === id) return item396					}397					return null398				}399				const result = produce(base, draft => {400					const obj1 = findById(draft, 1)401					const obj2 = findById(draft, 2)402					obj1.a = 2403					obj2.a = 2404				})405				expect(result).not.toBe(base)406				expect(result.get("first").a).toEqual(2)407				expect(result.get("second").a).toEqual(2)408			})409410			it("supports 'keys", () => {411				const base = new Map([412					["first", Symbol()],413					["second", Symbol()]414				])415				const result = produce(base, draft => {416					expect([...draft.keys()]).toEqual(["first", "second"])417					draft.set("third", Symbol())418					expect([...draft.keys()]).toEqual(["first", "second", "third"])419				})420			})421422			it("supports forEach", () => {423				const key1 = {prop: "val1"}424				const key2 = {prop: "val2"}425				const base = new Map([426					["first", {id: 1, a: 1}],427					["second", {id: 2, a: 1}],428					[key1, {id: 3, a: 1}],429					[key2, {id: 4, a: 1}]430				])431				const result = produce(base, draft => {432					let sum1 = 0433					draft.forEach(({a}) => {434						sum1 += a435					})436					expect(sum1).toBe(4)437					let sum2 = 0438					draft.get("first").a = 10439					draft.get("second").a = 20440					draft.get(key1).a = 30441					draft.get(key2).a = 40442					draft.forEach(({a}) => {443						sum2 += a444					})445					expect(sum2).toBe(100)446				})447				expect(result).not.toBe(base)448				expect(base.get("first").a).toEqual(1)449				expect(base.get("second").a).toEqual(1)450				expect(base.get(key1).a).toEqual(1)451				expect(base.get(key2).a).toEqual(1)452				expect(result.get("first").a).toEqual(10)453				expect(result.get("second").a).toEqual(20)454				expect(result.get(key1).a).toEqual(30)455				expect(result.get(key2).a).toEqual(40)456			})457458			it("supports forEach mutation", () => {459				const base = new Map([460					["first", {id: 1, a: 1}],461					["second", {id: 2, a: 1}]462				])463				const result = produce(base, draft => {464					draft.forEach(item => {465						item.a = 100466					})467				})468				expect(result).not.toBe(base)469				expect(result.get("first").a).toEqual(100)470				expect(result.get("second").a).toEqual(100)471			})472473			it("can assign by key", () => {474				const nextState = produce(baseState, s => {475					// Map.prototype.set should return the Map itself476					const res = s.aMap.set("force", true)477					if (!global.USES_BUILD) expect(res).toBe(s.aMap[DRAFT_STATE].draft_)478				})479				expect(nextState).not.toBe(baseState)480				expect(nextState.aMap).not.toBe(baseState.aMap)481				expect(nextState.aMap.get("force")).toEqual(true)482			})483484			it("can assign by a non-primitive key", () => {485				const key = {prop: "val"}486				const value = {id: 1, a: 1}487				const base = new Map([[key, value]])488				const nextState = produce(base, s => {489					s.set(key, true)490				})491				expect(nextState).not.toBe(base)492				expect(base.get(key)).toEqual(value)493				expect(nextState.get(key)).toEqual(true)494			})495496			it("state stays the same if the same item is assigned by key", () => {497				const nextState = produce(baseState, s => {498					s.aMap.set("jediTotal", 42)499				})500				expect(nextState).toBe(baseState)501				expect(nextState.aMap).toBe(baseState.aMap)502			})503504			it("returns 'size'", () => {505				const nextState = produce(baseState, s => {506					s.aMap.set("newKey", true)507					expect(s.aMap.size).toBe(baseState.aMap.size + 1)508				})509				expect(nextState).not.toBe(baseState)510				expect(nextState.aMap).not.toBe(baseState.aMap)511				expect(nextState.aMap.get("newKey")).toEqual(true)512				expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)513			})514515			it("can use 'delete' to remove items", () => {516				const nextState = produce(baseState, s => {517					expect(s.aMap.has("jedi")).toBe(true)518					expect(s.aMap.delete("jedi")).toBe(true)519					expect(s.aMap.has("jedi")).toBe(false)520				})521				expect(nextState.aMap).not.toBe(baseState.aMap)522				expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)523				expect(baseState.aMap.has("jedi")).toBe(true)524				expect(nextState.aMap.has("jedi")).toBe(false)525			})526527			it("can use 'clear' to remove items", () => {528				const nextState = produce(baseState, s => {529					expect(s.aMap.size).not.toBe(0)530					s.aMap.clear()531					expect(s.aMap.size).toBe(0)532				})533				expect(nextState.aMap).not.toBe(baseState.aMap)534				expect(baseState.aMap.size).not.toBe(0)535				expect(nextState.aMap.size).toBe(0)536			})537538			it("support 'has'", () => {539				const nextState = produce(baseState, s => {540					expect(s.aMap.has("newKey")).toBe(false)541					s.aMap.set("newKey", true)542					expect(s.aMap.has("newKey")).toBe(true)543				})544				expect(nextState).not.toBe(baseState)545				expect(nextState.aMap).not.toBe(baseState.aMap)546				expect(baseState.aMap.has("newKey")).toBe(false)547				expect(nextState.aMap.has("newKey")).toBe(true)548			})549550			it("supports nested maps", () => {551				const base = new Map([["first", new Map([["second", {prop: "test"}]])]])552				const result = produce(base, draft => {553					draft.get("first").get("second").prop = "test1"554				})555				expect(result).not.toBe(base)556				expect(result.get("first")).not.toBe(base.get("first"))557				expect(result.get("first").get("second")).not.toBe(558					base.get("first").get("second")559				)560				expect(base.get("first").get("second").prop).toBe("test")561				expect(result.get("first").get("second").prop).toBe("test1")562			})563564			it("treats void deletes as no-op", () => {565				const base = new Map([["x", 1]])566				const next = produce(base, d => {567					expect(d.delete("y")).toBe(false)568				})569				expect(next).toBe(base)570			})571572			it("revokes map proxies", () => {573				let m574				produce(baseState, s => {575					m = s.aMap576				})577				expect(() => m.get("x")).toThrowErrorMatchingSnapshot()578				expect(() => m.set("x", 3)).toThrowErrorMatchingSnapshot()579			})580581			it("does not draft map keys", () => {582				// anything else would be terribly confusing583				const key = {a: 1}584				const map = new Map([[key, 2]])585				const next = produce(map, d => {586					const dKey = Array.from(d.keys())[0]587					expect(isDraft(dKey)).toBe(false)588					expect(dKey).toBe(key)589					dKey.a += 1590					d.set(dKey, d.get(dKey) + 1)591					d.set(key, d.get(key) + 1)592					expect(d.get(key)).toBe(4)593					expect(key.a).toBe(2)594				})595				const entries = Array.from(next.entries())596				expect(entries).toEqual([[key, 4]])597				expect(entries[0][0]).toBe(key)598				expect(entries[0][0].a).toBe(2)599			})600601			it("does support instanceof Map", () => {602				const map = new Map()603				produce(map, d => {604					expect(d instanceof Map).toBeTruthy()605				})606			})607608			it("handles clear correctly", () => {609				const map = new Map([610					["a", 1],611					["c", 3]612				])613				const next = produce(map, draft => {614					draft.delete("a")615					draft.set("b", 2)616					draft.set("c", 4)617					draft.clear()618				})619				expect(next).toEqual(new Map())620			})621		})622623		describe("set drafts", () => {624			it("supports iteration", () => {625				const base = new Set([626					{id: 1, a: 1},627					{id: 2, a: 1}628				])629				const findById = (set, id) => {630					for (const item of set) {631						if (item.id === id) return item632					}633					return null634				}635				const result = produce(base, draft => {636					const obj1 = findById(draft, 1)637					const obj2 = findById(draft, 2)638					obj1.a = 2639					obj2.a = 2640				})641				expect(result).not.toBe(base)642				expect(base).toEqual(643					new Set([644						{id: 1, a: 1},645						{id: 2, a: 1}646					])647				)648				expect(result).toEqual(649					new Set([650						{id: 1, a: 2},651						{id: 2, a: 2}652					])653				)654			})655656			it("supports 'entries'", () => {657				const base = new Set([658					{id: 1, a: 1},659					{id: 2, a: 1}660				])661				const findById = (set, id) => {662					for (const [item1, item2] of set.entries()) {663						expect(item1).toBe(item2)664						if (item1.id === id) return item1665					}666					return null667				}668				const result = produce(base, draft => {669					const obj1 = findById(draft, 1)670					const obj2 = findById(draft, 2)671					obj1.a = 2672					obj2.a = 2673				})674				expect(result).not.toBe(base)675				expect(base).toEqual(676					new Set([677						{id: 1, a: 1},678						{id: 2, a: 1}679					])680				)681				expect(result).toEqual(682					new Set([683						{id: 1, a: 2},684						{id: 2, a: 2}685					])686				)687			})688689			it("supports 'values'", () => {690				const base = new Set([691					{id: 1, a: 1},692					{id: 2, a: 1}693				])694				const findById = (set, id) => {695					for (const item of set.values()) {696						if (item.id === id) return item697					}698					return null699				}700				const result = produce(base, draft => {701					const obj1 = findById(draft, 1)702					const obj2 = findById(draft, 2)703					obj1.a = 2704					obj2.a = 2705				})706				expect(result).not.toBe(base)707				expect(base).toEqual(708					new Set([709						{id: 1, a: 1},710						{id: 2, a: 1}711					])712				)713				expect(result).toEqual(714					new Set([715						{id: 1, a: 2},716						{id: 2, a: 2}717					])718				)719			})720721			it("supports 'keys'", () => {722				const base = new Set([723					{id: 1, a: 1},724					{id: 2, a: 1}725				])726				const findById = (set, id) => {727					for (const item of set.keys()) {728						if (item.id === id) return item729					}730					return null731				}732				const result = produce(base, draft => {733					const obj1 = findById(draft, 1)734					const obj2 = findById(draft, 2)735					obj1.a = 2736					obj2.a = 2737				})738				expect(result).not.toBe(base)739				expect(base).toEqual(740					new Set([741						{id: 1, a: 1},742						{id: 2, a: 1}743					])744				)745				expect(result).toEqual(746					new Set([747						{id: 1, a: 2},748						{id: 2, a: 2}749					])750				)751			})752753			it("supports forEach with mutation after reads", () => {754				const base = new Set([755					{id: 1, a: 1},756					{id: 2, a: 2}757				])758				const result = produce(base, draft => {759					let sum1 = 0760					draft.forEach(({a}) => {761						sum1 += a762					})763					expect(sum1).toBe(3)764					let sum2 = 0765					draft.forEach(item => {766						item.a += 10767						sum2 += item.a768					})769					expect(sum2).toBe(23)770				})771				expect(result).not.toBe(base)772				expect(base).toEqual(773					new Set([774						{id: 1, a: 1},775						{id: 2, a: 2}776					])777				)778				expect(result).toEqual(779					new Set([780						{id: 1, a: 11},781						{id: 2, a: 12}782					])783				)784			})785786			it("state stays the same if the same item is added", () => {787				const nextState = produce(baseState, s => {788					s.aSet.add("Luke")789				})790				expect(nextState).toBe(baseState)791				expect(nextState.aSet).toBe(baseState.aSet)792			})793794			it("can add new items", () => {795				const nextState = produce(baseState, s => {796					// Set.prototype.set should return the Set itself797					const res = s.aSet.add("force")798					if (!global.USES_BUILD) expect(res).toBe(s.aSet[DRAFT_STATE].draft_)799				})800				expect(nextState).not.toBe(baseState)801				expect(nextState.aSet).not.toBe(baseState.aSet)802				expect(baseState.aSet.has("force")).toBe(false)803				expect(nextState.aSet.has("force")).toBe(true)804			})805806			it("returns 'size'", () => {807				const nextState = produce(baseState, s => {808					s.aSet.add("newKey")809					expect(s.aSet.size).toBe(baseState.aSet.size + 1)810				})811				expect(nextState).not.toBe(baseState)812				expect(nextState.aSet).not.toBe(baseState.aSet)813				expect(nextState.aSet.has("newKey")).toBe(true)814				expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)815			})816817			it("can use 'delete' to remove items", () => {818				const nextState = produce(baseState, s => {819					expect(s.aSet.has("Luke")).toBe(true)820					expect(s.aSet.delete("Luke")).toBe(true)821					expect(s.aSet.delete("Luke")).toBe(false)822					expect(s.aSet.has("Luke")).toBe(false)823				})824				expect(nextState.aSet).not.toBe(baseState.aSet)825				expect(baseState.aSet.has("Luke")).toBe(true)826				expect(nextState.aSet.has("Luke")).toBe(false)827				expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)828			})829830			it("can use 'clear' to remove items", () => {831				const nextState = produce(baseState, s => {832					expect(s.aSet.size).not.toBe(0)833					s.aSet.clear()834					expect(s.aSet.size).toBe(0)835				})836				expect(nextState.aSet).not.toBe(baseState.aSet)837				expect(baseState.aSet.size).not.toBe(0)838				expect(nextState.aSet.size).toBe(0)839			})840841			it("supports 'has'", () => {842				const nextState = produce(baseState, s => {843					expect(s.aSet.has("newKey")).toBe(false)844					s.aSet.add("newKey")845					expect(s.aSet.has("newKey")).toBe(true)846				})847				expect(nextState).not.toBe(baseState)848				expect(nextState.aSet).not.toBe(baseState.aSet)849				expect(baseState.aSet.has("newKey")).toBe(false)850				expect(nextState.aSet.has("newKey")).toBe(true)851			})852853			it("supports nested sets", () => {854				const base = new Set([new Set(["Serenity"])])855				const result = produce(base, draft => {856					draft.forEach(nestedItem => nestedItem.add("Firefly"))857				})858				expect(result).not.toBe(base)859				expect(base).toEqual(new Set([new Set(["Serenity"])]))860				expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))861			})862863			it("supports has / delete on elements from the original", () => {864				const obj = {}865				const set = new Set([obj])866				const next = produce(set, d => {867					expect(d.has(obj)).toBe(true)868					d.add(3)869					expect(d.has(obj)).toBe(true)870					d.delete(obj)871					expect(d.has(obj)).toBe(false)872				})873				expect(next).toEqual(new Set([3]))874			})875876			it("revokes sets", () => {877				let m878				produce(baseState, s => {879					m = s.aSet880				})881				expect(() => m.has("x")).toThrowErrorMatchingSnapshot()882				expect(() => m.add("x")).toThrowErrorMatchingSnapshot()883			})884885			it("does support instanceof Set", () => {886				const set = new Set()887				produce(set, d => {888					expect(d instanceof Set).toBeTruthy()889				})890			})891		})892893		it("supports `immerable` symbol on constructor", () => {894			class One {}895			One[immerable] = true896			const baseState = new One()897			const nextState = produce(baseState, draft => {898				expect(draft).not.toBe(baseState)899				draft.foo = true900			})901			expect(nextState).not.toBe(baseState)902			expect(nextState.foo).toBeTruthy()903		})904905		it("preserves symbol properties", () => {906			const test = Symbol("test")907			const baseState = {[test]: true}908			const nextState = produce(baseState, s => {909				expect(s[test]).toBeTruthy()910				s.foo = true911			})912			expect(nextState).toEqual({913				[test]: true,914				foo: true915			})916		})917918		if (!global.USES_BUILD)919			it("preserves non-enumerable properties", () => {920				const baseState = {}921				// Non-enumerable object property922				Object.defineProperty(baseState, "foo", {923					value: {a: 1},924					enumerable: false925				})926				// Non-enumerable primitive property927				Object.defineProperty(baseState, "bar", {928					value: 1,929					enumerable: false930				})931				// Non-enumerable primitive property that won't modified.932				Object.defineProperty(baseState, "baz", {933					value: 1,934					enumerable: false935				})936937				// When using Proxy, even non-enumerable keys will be copied if it's changed.938				const canReferNonEnumerableProperty = useStrictShallowCopy939				const nextState = produce(baseState, s => {940					if (canReferNonEnumerableProperty) expect(s.foo).toBeTruthy()941					if (useStrictShallowCopy) expect(isEnumerable(s, "foo")).toBeFalsy()942					if (canReferNonEnumerableProperty) s.bar++943					if (useStrictShallowCopy) expect(isEnumerable(s, "foo")).toBeFalsy()944					if (canReferNonEnumerableProperty) s.foo.a++945					if (useStrictShallowCopy) expect(isEnumerable(s, "foo")).toBeFalsy()946				})947				if (canReferNonEnumerableProperty) {948					expect(nextState.foo).toEqual({a: 2})949				}950				if (useStrictShallowCopy)951					expect(isEnumerable(nextState, "foo")).toBeFalsy()952				if (useStrictShallowCopy) expect(nextState.baz).toBeTruthy()953			})954955		it("can work with own computed props", () => {956			const baseState = {957				x: 1,958				get y() {959					return this.x960				},961				set y(v) {962					this.x = v963				}964			}965966			const nextState = produce(baseState, d => {967				expect(d.y).toBe(1)968				d.x = 2969				expect(d.x).toBe(2)970				expect(d.y).toBe(1) // this has been copied!971				d.y = 3972				expect(d.x).toBe(2)973			})974			expect(baseState.x).toBe(1)975			expect(baseState.y).toBe(1)976977			expect(nextState.x).toBe(2)978			expect(nextState.y).toBe(3)979			if (!autoFreeze) {980				nextState.y = 4 // decoupled now!981				expect(nextState.y).toBe(4)982				expect(nextState.x).toBe(2)983				expect(Object.getOwnPropertyDescriptor(nextState, "y").value).toBe(4)984			}985		})986987		it("can work with class with computed props", () => {988			class State {989				[immerable] = true990991				x = 1992993				set y(v) {994					this.x = v995				}996997				get y() {998					return this.x999				}1000			}10011002			const baseState = new State()10031004			const nextState = produce(baseState, d => {1005				expect(d.y).toBe(1)1006				d.y = 21007				expect(d.x).toBe(2)1008				expect(d.y).toBe(2)1009				expect(Object.getOwnPropertyDescriptor(d, "y")).toBeUndefined()1010			})1011			expect(baseState.x).toBe(1)1012			expect(baseState.y).toBe(1)10131014			expect(nextState.x).toBe(2)1015			expect(nextState.y).toBe(2)1016			expect(Object.getOwnPropertyDescriptor(nextState, "y")).toBeUndefined()1017		})10181019		it("allows inherited computed properties", () => {1020			const proto = {}1021			Object.defineProperty(proto, "foo", {1022				get() {1023					return this.bar1024				},1025				set(val) {1026					this.bar = val1027				}1028			})1029			proto[immerable] = true1030			const baseState = Object.create(proto)1031			produce(baseState, s => {1032				expect(s.bar).toBeUndefined()1033				s.foo = {}1034				expect(s.bar).toBeDefined()1035				expect(s.foo).toBe(s.bar)1036			})1037		})10381039		it("optimization: does not visit properties of new data structures if autofreeze is disabled and no drafts are unfinalized", () => {1040			const newData = {}1041			Object.defineProperty(newData, "x", {1042				enumerable: true,1043				get() {1044					throw new Error("visited!")1045				}1046			})10471048			const run = () =>1049				produce({}, d => {1050					d.data = newData1051				})1052			if (autoFreeze) {1053				expect(run).toThrow("visited!")1054			} else {1055				expect(run).not.toThrow("visited!")1056			}1057		})10581059		it("same optimization doesn't cause draft from nested producers to be unfinished", () => {1060			const base = {1061				y: 1,1062				child: {1063					x: 11064				}1065			}1066			const wrap = produce(draft => {1067				return {1068					wrapped: draft1069				}1070			})10711072			const res = produce(base, draft => {1073				draft.y++1074				draft.child = wrap(draft.child)1075				draft.child.wrapped.x++1076			})10771078			expect(res).toEqual({1079				y: 2,1080				child: {wrapped: {x: 2}}1081			})1082		})10831084		it("supports a base state with multiple references to an object", () => {1085			const obj = {}1086			const res = produce({a: obj, b: obj}, d => {1087				// Two drafts are created for each occurrence of an object in the base state.1088				expect(d.a).not.toBe(d.b)1089				d.a.z = true1090				expect(d.b.z).toBeUndefined()1091			})1092			expect(res.b).toBe(obj)1093			expect(res.a).not.toBe(res.b)1094			expect(res.a.z).toBeTruthy()1095		})10961097		// NOTE: Except the root draft.1098		it("supports multiple references to any modified draft", () => {1099			const next = produce({a: {b: 1}}, d => {1100				d.a.b++1101				d.b = d.a1102			})1103			expect(next.a).toBe(next.b)1104		})11051106		it("can rename nested objects (no changes)", () => {1107			const nextState = produce({obj: {}}, s => {1108				s.foo = s.obj1109				delete s.obj1110			})1111			expect(nextState).toEqual({foo: {}})1112		})11131114		// Very similar to the test before, but the reused object has one1115		// property changed, one added, and one removed.1116		it("can rename nested objects (with changes)", () => {1117			const nextState = produce({obj: {a: 1, b: 1}}, s => {1118				s.obj.a = true // change1119				delete s.obj.b // delete1120				s.obj.c = true // add11211122				s.foo = s.obj1123				delete s.obj1124			})1125			expect(nextState).toEqual({foo: {a: true, c: true}})1126		})11271128		it("can nest a draft in a new object (no changes)", () => {1129			const baseState = {obj: {}}1130			const nextState = produce(baseState, s => {1131				s.foo = {bar: s.obj}1132				delete s.obj1133			})1134			expect(nextState.foo.bar).toBe(baseState.obj)1135		})11361137		it("can nest a modified draft in a new object", () => {1138			const nextState = produce({obj: {a: 1, b: 1}}, s => {1139				s.obj.a = true // change1140				delete s.obj.b // delete1141				s.obj.c = true // add11421143				s.foo = {bar: s.obj}1144				delete s.obj1145			})1146			expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1147		})11481149		it("supports assigning undefined to an existing property", () => {1150			const nextState = produce(baseState, s => {1151				s.aProp = undefined1152			})1153			expect(nextState).not.toBe(baseState)1154			expect(nextState.aProp).toBe(undefined)1155		})11561157		it("supports assigning undefined to a new property", () => {1158			const baseState = {}1159			const nextState = produce(baseState, s => {1160				s.aProp = undefined1161			})1162			expect(nextState).not.toBe(baseState)1163			expect(nextState.aProp).toBe(undefined)1164		})11651166		// NOTE: ES5 drafts only protect existing properties when revoked.1167		if (!isProd)1168			it("revokes the draft once produce returns", () => {1169				const expectRevoked = fn => {1170					expect(fn).toThrowErrorMatchingSnapshot()1171				}11721173				// Test object drafts:1174				let draft1175				produce({a: 1, b: 1}, s => {1176					draft = s1177					delete s.b1178				})11791180				// Access known property on object draft.1181				expectRevoked(() => {1182					draft.a1183				})11841185				// Assign known property on object draft.1186				expectRevoked(() => {1187					draft.a = true1188				})11891190				// Access unknown property on object draft.1191				expectRevoked(() => {1192					draft.z1193				})11941195				// Assign unknown property on object draft.1196				expectRevoked(() => {1197					draft.z = true1198				})11991200				// Test array drafts:1201				produce([1, 2], s => {1202					draft = s1203					s.pop()1204				})12051206				// Access known index of an array draft.1207				expectRevoked(() => {1208					draft[0]1209				})12101211				// Assign known index of an array draft.1212				expectRevoked(() => {1213					draft[0] = true1214				})12151216				// Access unknown index of an array draft.1217				expectRevoked(() => {1218					draft[1]1219				})12201221				// Assign unknown index of an array draft.1222				expectRevoked(() => {1223					draft[1] = true1224				})1225			})12261227		it("can access a child draft that was created before the draft was modified", () => {1228			produce({a: {}}, s => {1229				const before = s.a1230				s.b = 11231				expect(s.a).toBe(before)1232			})1233		})12341235		it("should reflect all changes made in the draft immediately", () => {1236			produce(baseState, draft => {1237				draft.anArray[0] = 51238				draft.anArray.unshift("test")1239				if (!global.USES_BUILD)1240					expect(enumerableOnly(draft.anArray)).toEqual([1241						"test",1242						5,1243						2,1244						{c: 3},1245						11246					])1247				draft.stuffz = "coffee"1248				expect(draft.stuffz).toBe("coffee")1249			})1250		})12511252		it("throws when Object.defineProperty() is used on drafts", () => {1253			expect(() => {1254				produce({}, draft => {1255					Object.defineProperty(draft, "xx", {1256						enumerable: true,1257						writeable: true,1258						value: 21259					})1260				})1261			}).toThrowErrorMatchingSnapshot()1262		})12631264		it("should handle constructor correctly", () => {1265			const baseState = {1266				arr: new Array(),1267				obj: new Object()1268			}1269			const result = produce(baseState, draft => {1270				draft.arrConstructed = draft.arr.constructor(1)1271				draft.objConstructed = draft.obj.constructor(1)1272			})1273			expect(result.arrConstructed).toEqual(new Array().constructor(1))1274			expect(result.objConstructed).toEqual(new Object().constructor(1))1275		})12761277		it("should handle equality correctly - 1", () => {1278			const baseState = {1279				y: 3 / 0,1280				z: NaN1281			}1282			const nextState = produce(baseState, draft => {1283				draft.y = 4 / 01284				draft.z = NaN1285			})1286			expect(nextState).toBe(baseState)1287		})12881289		it("should handle equality correctly - 2", () => {1290			const baseState = {1291				x: -01292			}1293			const nextState = produce(baseState, draft => {1294				draft.x = +01295			})1296			// 0 === -0 // true1297			// Object.is(0, -0) // false1298			//1299			// MWE:1300			// Immer preserves the difference between -0 and +0,1301			// so a new state is created.1302			// This isn't defined anywhere explicitly, so could be changed1303			// in the future to follow === behavior, rather than Object.is.1304			// But I think this is fine as is.1305			expect(nextState).not.toBe(baseState)1306			expect(nextState.x).toBe(-0)1307			expect(nextState.x).not.toBe(+0)1308			// however, toEqual treats -0 === +0 (which is true!)1309			expect(nextState).toEqual(baseState)1310		})13111312		it("should handle equality correctly - 3", () => {1313			const baseState = {1314				x: "s1",1315				y: 1,1316				z: NaN1317			}1318			const nextState = produce(baseState, draft => {1319				draft.x = "s2"1320				draft.y = 11321				draft.z = NaN1322				if (!isProd) {1323					expect(draft[DRAFT_STATE].assigned_.x).toBe(true)1324					expect(draft[DRAFT_STATE].assigned_.y).toBe(undefined)1325					expect(draft[DRAFT_STATE].assigned_.z).toBe(undefined)1326				}1327			})1328			expect(nextState.x).toBe("s2")1329		})13301331		// AKA: recursive produce calls1332		describe("nested producers", () => {1333			describe("when base state is not a draft", () => {1334				// This test ensures the global state used to manage proxies is1335				// never left in a corrupted state by a nested `produce` call.1336				it("never affects its parent producer implicitly", () => {1337					const base = {obj: {a: 1}}1338					const next = produce(base, draft => {1339						// Notice how `base.obj` is passed, not `draft.obj`1340						const obj2 = produce(base.obj, draft2 => {1341							draft2.a = 01342						})1343						expect(obj2.a).toBe(0)1344						expect(draft.obj.a).toBe(1) // effects should not be visible outside1345					})1346					expect(next).toBe(base)1347				})1348			})13491350			describe("when base state is a draft", () => {1351				it("always wraps the draft in a new draft", () => {1352					produce({}, parent => {1353						produce(parent, child => {1354							expect(child).not.toBe(parent)1355							expect(isDraft(child)).toBeTruthy()1356							expect(original(child)).toBe(parent)1357						})1358					})1359				})13601361				// Reported by: https://github.com/mweststrate/immer/issues/3431362				it("ensures each property is drafted", () => {1363					produce({a: {}, b: {}}, parent => {1364						parent.a // Access "a" but not "b"1365						produce(parent, child => {1366							child.c = 11367							expect(isDraft(child.a)).toBeTruthy()1368							expect(isDraft(child.b)).toBeTruthy()1369						})1370					})1371				})13721373				it("preserves any pending changes", () => {1374					produce({a: 1, b: 1, d: 1}, parent => {1375						parent.b = 21376						parent.c = 21377						delete parent.d1378						produce(parent, child => {1379							expect(child.a).toBe(1) // unchanged1380							expect(child.b).toBe(2) // changed1381							expect(child.c).toBe(2) // added1382							expect(child.d).toBeUndefined() // deleted1383						})1384					})1385				})1386			})13871388			describe("when base state contains a draft", () => {1389				it("wraps unowned draft with its own draft", () => {1390					produce({a: {}}, parent => {1391						produce({a: parent.a}, child => {1392							expect(child.a).not.toBe(parent.a)1393							expect(isDraft(child.a)).toBeTruthy()1394							expect(original(child.a)).toBe(parent.a)1395						})1396					})1397				})13981399				it("returns unowned draft if no changes were made", () => {1400					produce({a: {}}, parent => {1401						const result = produce({a: parent.a}, () => {})1402						expect(result.a).toBe(parent.a)1403					})1404				})14051406				it("clones the unowned draft when changes are made", () => {1407					produce({a: {}}, parent => {1408						const result = produce({a: parent.a}, child => {1409							child.a.b = 11410						})1411						expect(result.a).not.toBe(parent.a)1412						expect(result.a.b).toBe(1)1413						expect("b" in parent.a).toBeFalsy()1414					})1415				})14161417				// We cannot auto-freeze the result of a nested producer,1418				// because it may contain a draft from a parent producer.1419				it("never auto-freezes the result", () => {1420					produce({a: {}}, parent => {1421						const r = produce({a: parent.a}, child => {1422							child.b = 1 // Ensure a copy is returned.1423						})1424						expect(Object.isFrozen(r)).toBeFalsy()1425					})1426				})1427			})14281429			// "Upvalues" are variables from a parent scope.1430			it("does not finalize upvalue drafts", () => {1431				produce({a: {}, b: {}}, parent => {1432					expect(produce({}, () => parent)).toBe(parent)1433					parent.x // Ensure proxy not revoked.14341435					expect(produce({}, () => [parent])[0]).toBe(parent)1436					parent.x // Ensure proxy not revoked.14371438					expect(produce({}, () => parent.a)).toBe(parent.a)1439					parent.a.x // Ensure proxy not revoked.14401441					// Modified parent test1442					parent.c = 11443					expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1444					parent.b.x // Ensure proxy not revoked.1445				})1446			})14471448			it("works with interweaved Immer instances", () => {1449				const options = {autoFreeze}1450				const one = createPatchedImmer(options)1451				const two = createPatchedImmer(options)14521453				const base = {}1454				const result = one.produce(base, s1 =>1455					two.produce({s1}, s2 => {1456						expect(original(s2.s1)).toBe(s1)1457						s2.n = 11458						s2.s1 = one.produce({s2}, s3 => {1459							expect(original(s3.s2)).toBe(s2)1460							expect(original(s3.s2.s1)).toBe(s2.s1)1461							return s3.s2.s11462						})1463					})1464				)1465				expect(result.n).toBe(1)1466				expect(result.s1).toBe(base)1467			})1468		})14691470		it("throws when Object.setPrototypeOf() is used on a draft", () => {1471			produce({}, draft => {1472				expect(() =>1473					Object.setPrototypeOf(draft, Array)1474				).toThrowErrorMatchingSnapshot()1475			})1476		})14771478		it("supports the 'in' operator", () => {1479			produce(baseState, draft => {1480				// Known property1481				expect("anArray" in draft).toBe(true)1482				expect(Reflect.has(draft, "anArray")).toBe(true)14831484				// Unknown property1485				expect("bla" in draft).toBe(false)1486				expect(Reflect.has(draft, "bla")).toBe(false)14871488				// Known index1489				expect(0 in draft.anArray).toBe(true)1490				expect("0" in draft.anArray).toBe(true)1491				expect(Reflect.has(draft.anArray, 0)).toBe(true)1492				expect(Reflect.has(draft.anArray, "0")).toBe(true)14931494				// Unknown index1495				expect(17 in draft.anArray).toBe(false)1496				expect("17" in draft.anArray).toBe(false)1497				expect(Reflect.has(draft.anArray, 17)).toBe(false)1498				expect(Reflect.has(draft.anArray, "17")).toBe(false)1499			})1500		})15011502		it("'this' should not be bound anymore - 1", () => {1503			const base = {x: 3}1504			const next1 = produce(base, function() {1505				expect(this).toBe(undefined)1506			})1507		})15081509		it("'this' should not be bound anymore - 2", () => {1510			const incrementor = produce(function() {1511				expect(this).toBe(undefined)1512			})1513			incrementor()1514		})15151516		it("should be possible to use dynamic bound this", () => {1517			const world = {1518				counter: {count: 1},1519				inc: produce(function(draft) {1520					expect(this).toBe(world)1521					draft.counter.count = this.counter.count + 11522				})1523			}15241525			expect(world.inc(world).counter.count).toBe(2)1526		})15271528		it("doesnt recurse into frozen structures if external data is frozen", () => {1529			const frozen = {}1530			Object.defineProperty(frozen, "x", {1531				get() {1532					throw "oops"1533				},1534				enumerable: true,1535				configurable: true1536			})1537			Object.freeze(frozen)15381539			expect(() => {1540				produce({}, d => {1541					d.x = frozen1542				})1543			}).not.toThrow()1544		})15451546		// See here: https://github.com/mweststrate/immer/issues/891547		it("supports the spread operator", () => {1548			const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1549			const result = produce(base, draft => {1550				draft.foo = {x: 1, ...draft.foo, y: 1}1551				draft.bar = [1, ...draft.bar, 1]1552			})1553			expect(result).toEqual({1554				foo: {x: 0, y: 1},1555				bar: [1, 0, 0, 1]1556			})1557		})15581559		it("processes with lodash.set", () => {1560			const base = [{id: 1, a: 1}]1561			const result = produce(base, draft => {1562				lodash.set(draft, "[0].a", 2)1563			})1564			expect(base[0].a).toEqual(1)1565			expect(result[0].a).toEqual(2)1566		})15671568		it("processes with lodash.find", () => {1569			const base = [{id: 1, a: 1}]1570			const result = produce(base, draft => {1571				const obj1 = lodash.find(draft, {id: 1})1572				lodash.set(obj1, "a", 2)1573			})1574			expect(base[0].a).toEqual(1)1575			expect(result[0].a).toEqual(2)1576		})15771578		it("does not draft external data", () => {1579			const externalData = {x: 3}1580			const base = {}1581			const next = produce(base, draft => {1582				// potentially, we *could* draft external data automatically, but only if those statements are not switched...1583				draft.y = externalData1584				draft.y.x += 11585				externalData.x += 11586			})1587			expect(next).toEqual({y: {x: 5}})1588			expect(externalData.x).toBe(5)1589			expect(next.y).toBe(externalData)1590		})15911592		it("does not create new state unnecessary, #491", () => {1593			const a = {highlight: true}1594			const next1 = produce(a, draft => {1595				draft.highlight = false1596				draft.highlight = true1597			})1598			// See explanation in issue1599			expect(next1).not.toBe(a)16001601			const next2 = produce(a, draft => {1602				draft.highlight = true1603			})1604			expect(next2).toBe(a)1605		})16061607		autoFreeze &&1608			test("issue #462 - frozen", () => {1609				var origin = {1610					a: {1611						value: "no"1612					},1613					b: {1614						value: "no"1615					}1616				}1617				const next = produce(origin, draft => {1618					draft.a.value = "im"1619				})1620				expect(() => {1621					origin.b.value = "yes"1622				}).toThrowError(1623					"Cannot assign to read only property 'value' of object '#<Object>'"1624				)1625				expect(() => {1626					next.b.value = "yes"1627				}).toThrowError(1628					"Cannot assign to read only property 'value' of object '#<Object>'"1629				) // should throw!1630			})16311632		autoFreeze &&1633			test("issue #469, state not frozen", () => {1634				const project = produce(1635					{1636						id: 1,1637						tracks: [{id: 1}]1638					},1639					() => {}1640				)16411642				expect(() => {1643					project.id = 2 // Does not throw error1644				}).toThrowError("Cannot assign to read only property 'id'")16451646				expect(() => {1647					Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1648				}).toThrowError("Cannot assign to read only property 'id'")1649			})16501651		describe("recipe functions", () => {1652			it("can return a new object", () => {1653				const base = {x: 3}1654				const res = produce(base, d => {1655					return {x: d.x + 1}1656				})1657				expect(res).not.toBe(base)1658				expect(res).toEqual({x: 4})1659			})16601661			it("can return the draft", () => {1662				const base = {x: 3}1663				const res = produce(base, d => {1664					d.x = 41665					return d1666				})1667				expect(res).not.toBe(base)1668				expect(res).toEqual({x: 4})1669			})16701671			it("can return an unmodified child draft", () => {1672				const base = {a: {}}1673				const res = produce(base, d => {1674					return d.a1675				})1676				expect(res).toBe(base.a)1677			})16781679			// TODO: Avoid throwing if only the child draft was modified.1680			it("cannot return a modified child draft", () => {1681				const base = {a: {}}1682				expect(() => {1683					produce(base, d => {1684						d.a.b = 11685						return d.a1686					})1687				}).toThrowErrorMatchingSnapshot()1688			})16891690			it("can return a frozen object", () => {1691				const res = deepFreeze([{x: 3}])1692				expect(produce({}, () => res)).toBe(res)1693			})16941695			it("can return an object with two references to another object", () => {1696				const next = produce({}, d => {1697					const obj = {}1698					return {obj, arr: [obj]}1699				})1700				expect(next.obj).toBe(next.arr[0])1701			})17021703			it("can return an object with two references to an unmodified draft", () => {1704				const base = {a: {}}1705				const next = produce(base, d => {1706					return [d.a, d.a]1707				})1708				expect(next[0]).toBe(base.a)1709				expect(next[0]).toBe(next[1])1710			})17111712			it("cannot return an object that references itself", () => {1713				const res = {}1714				res.self = res1715				expect(() => {1716					produce(res, () => res.self)1717				}).toThrowErrorMatchingSnapshot()1718			})1719		})17201721		it("throws when the draft is modified and another object is returned", () => {1722			const base = {x: 3}1723			expect(() => {1724				produce(base, draft => {1725					draft.x = 41726					return {x: 5}1727				})1728			}).toThrowErrorMatchingSnapshot()1729		})17301731		it("should fix #117 - 1", () => {1732			const reducer = (state, action) =>1733				produce(state, draft => {1734					switch (action.type) {1735						case "SET_STARTING_DOTS":1736							return draft.availableStartingDots.map(a => a)1737						default:1738							break1739					}1740				})1741			const base = {1742				availableStartingDots: [1743					{dots: 4, count: 1},1744					{dots: 3, count: 2},1745					{dots: 2, count: 3},1746					{dots: 1, count: 4}1747				]1748			}1749			const next = reducer(base, {type: "SET_STARTING_DOTS"})1750			expect(next).toEqual(base.availableStartingDots)1751			expect(next).not.toBe(base.availableStartingDots)1752		})17531754		it("should fix #117 - 2", () => {1755			const reducer = (state, action) =>1756				produce(state, draft => {1757					switch (action.type) {1758						case "SET_STARTING_DOTS":1759							return {1760								dots: draft.availableStartingDots.map(a => a)1761							}1762						default:1763							break1764					}1765				})1766			const base = {1767				availableStartingDots: [1768					{dots: 4, count: 1},1769					{dots: 3, count: 2},1770					{dots: 2, count: 3},1771					{dots: 1, count: 4}1772				]1773			}1774			const next = reducer(base, {type: "SET_STARTING_DOTS"})1775			expect(next).toEqual({dots: base.availableStartingDots})1776		})17771778		it("cannot always detect noop assignments - 0", () => {1779			const baseState = {x: {y: 3}}1780			const nextState = produce(baseState, d => {1781				const a = d.x1782				d.x = a1783			})1784			expect(nextState).toBe(baseState)1785		})17861787		it("cannot always detect noop assignments - 1", () => {1788			const baseState = {x: {y: 3}}1789			const nextState = produce(baseState, d => {1790				const a = d.x1791				d.x = 41792				d.x = a1793			})1794			// Ideally, this should actually be the same instances1795			// but this would be pretty expensive to detect,1796			// so we don't atm1797			expect(nextState).not.toBe(baseState)1798		})17991800		it("cannot always detect noop assignments - 2", () => {1801			const baseState = {x: {y: 3}}1802			const nextState = produce(baseState, d => {1803				const a = d.x1804				const stuff = a.y + 31805				d.x = 41806				d.x = a1807			})1808			// Ideally, this should actually be the same instances1809			// but this would be pretty expensive to detect,1810			// so we don't atm1811			expect(nextState).not.toBe(baseState)1812		})18131814		it("cannot always detect noop assignments - 3", () => {1815			const baseState = {x: 3}1816			const nextState = produce(baseState, d => {1817				d.x = 31818			})1819			expect(nextState).toBe(baseState)1820		})18211822		it("cannot always detect noop assignments - 4", () => {1823			const baseState = {x: 3}1824			const nextState = produce(baseState, d => {1825				d.x = 41826				d.x = 31827			})1828			// Ideally, this should actually be the same instances1829			// but this would be pretty expensive to detect,1830			// so we don't atm1831			expect(nextState).not.toBe(baseState)1832		})18331834		it("cannot always detect noop assignments - 4", () => {1835			const baseState = {}1836			const [nextState, patches] = produceWithPatches(baseState, d => {1837				d.x = 41838				delete d.x1839			})1840			expect(nextState).toEqual({})1841			expect(patches).toEqual([])1842			// This differs between ES5 and proxy, and ES5 does it better :(1843			expect(nextState).not.toBe(baseState)1844		})18451846		it("cannot produce undefined by returning undefined", () => {1847			const base = 31848			expect(produce(base, () => 4)).toBe(4)1849			expect(produce(base, () => null)).toBe(null)1850			expect(produce(base, () => undefined)).toBe(3)1851			expect(produce(base, () => {})).toBe(3)1852			expect(produce(base, () => nothing)).toBe(undefined)18531854			expect(produce({}, () => undefined)).toEqual({})1855			expect(produce({}, () => nothing)).toBe(undefined)1856			expect(produce(3, () => nothing)).toBe(undefined)18571858			expect(produce(() => undefined)({})).toEqual({})1859			expect(produce(() => nothing)({})).toBe(undefined)1860			expect(produce(() => nothing)(3)).toBe(undefined)1861		})18621863		describe("base state type", () => {1864			if (!global.USES_BUILD) testObjectTypes(produce)1865			testLiteralTypes(produce)1866		})18671868		afterEach(() => {1869			expect(baseState).toBe(origBaseState)1870			expect(baseState).toEqual(createBaseState())1871		})18721873		function createBaseState() {1874			const data = {1875				anInstance: new Foo(),1876				anArray: [3, 2, {c: 3}, 1],1877				aMap: new Map([1878					["jedi", {name: "Luke", skill: 10}],1879					["jediTotal", 42],1880					["force", "these aren't the droids you're looking for"]1881				]),1882				aSet: new Set([1883					"Luke",1884					42,1885					{1886						jedi: "Yoda"1887					}1888				]),1889				aProp: "hi",1890				anObject: {1891					nested: {1892						yummie: true1893					},1894					coffee: false1895				}1896			}1897			return autoFreeze ? deepFreeze(data) : data1898		}1899	})19001901	it(`works with spread #524 - ${name}`, () => {1902		const state = {1903			level1: {1904				level2: {1905					level3: "data"1906				}1907			}1908		}19091910		const nextState = produce(state, draft => {1911			return {...draft}1912		})1913		const nextState1 = produce(state, draft => {1914			const newLevel1 = produce(draft.level1, level1Draft => {1915				return {...level1Draft}1916			})1917			draft.level1 = newLevel11918		})19191920		const nextState2 = produce(state, draft => {1921			const newLevel1 = produce(draft.level1, level1Draft => {1922				return {...level1Draft}1923			})1924			return {1925				level1: newLevel11926			}1927		})19281929		const nextState3 = produce(state, draft => {1930			const newLevel1 = produce(draft.level1, level1Draft => {1931				return Object.assign({}, level1Draft)1932			})1933			return Object.assign(draft, {1934				level1: newLevel11935			})1936		})19371938		const expected = {level1: {level2: {level3: "data"}}}1939		expect(nextState1).toEqual(expected)1940		expect(nextState2).toEqual(expected)1941		expect(nextState3).toEqual(expected)1942	})19431944	it(`Something with nested producers #522 ${name}`, () => {1945		function initialStateFactory() {1946			return {1947				substate: {1948					array: [1949						{id: "id1", value: 0},1950						{id: "id2", value: 0}1951					]1952				},1953				array: [1954					{id: "id1", value: 0},1955					{id: "id2", value: 0}1956				]1957			}1958		}19591960		const globalProducer = produce(draft => {1961			draft.substate = subProducer(draft.substate)1962			draft.array = arrayProducer(draft.array)1963		}, initialStateFactory())19641965		const subProducer = produce(draftSubState => {1966			draftSubState.array = arrayProducer(draftSubState.array)1967		})19681969		const arrayProducer = produce(draftArray => {1970			draftArray[0].value += 51971		})19721973		{1974			const state = globalProducer(undefined)1975			expect(state.array[0].value).toBe(5)1976			expect(state.array.length).toBe(2)1977			expect(state.array[1]).toMatchObject({1978				id: "id2",1979				value: 01980			})1981		}19821983		{1984			const state = globalProducer(undefined)1985			expect(state.substate.array[0].value).toBe(5)1986			expect(state.substate.array.length).toBe(2)1987			expect(state.substate.array[1]).toMatchObject({1988				id: "id2",1989				value: 01990			})1991			expect(state.substate.array).toMatchObject(state.array)1992		}1993	})19941995	describe(`isDraft - ${name}`, () => {1996		it("returns true for object drafts", () => {1997			produce({}, state => {1998				expect(isDraft(state)).toBeTruthy()1999			})2000		})

The first 2,000 of 2,459 lines.