Skip to content
Myr

base.js

This file

Path

__tests__/base.js

2,500 lines · 62.9 KiB · JavaScript

Last changed by

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

History of this file

Take it

1"use strict"2import {3	Immer,4	nothing,5	original,6	isDraft,7	immerable,8	enableAllPlugins9} from "../src/immer"10import {each, shallowCopy, DRAFT_STATE} from "../src/internal"11import deepFreeze from "deep-freeze"12import cloneDeep from "lodash.clonedeep"13import * as lodash from "lodash"1415jest.setTimeout(1000)1617enableAllPlugins()1819const isProd = process.env.NODE_ENV === "production"2021test("immer should have no dependencies", () => {22	expect(require("../package.json").dependencies).toBeUndefined()23})2425runBaseTest("proxy (no freeze)", true, false)26runBaseTest("proxy (autofreeze)", true, true)27runBaseTest("proxy (patch listener)", true, false, true)28runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)2930runBaseTest("es5 (no freeze)", false, false)31runBaseTest("es5 (autofreeze)", false, true)32runBaseTest("es5 (patch listener)", false, false, true)33runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)3435function runBaseTest(name, useProxies, autoFreeze, useListener) {36	const listener = useListener ? function() {} : undefined37	const {produce, produceWithPatches} = createPatchedImmer({38		useProxies,39		autoFreeze40	})4142	// When `useListener` is true, append a function to the arguments of every43	// uncurried `produce` call in every test. This makes tests easier to read.44	function createPatchedImmer(options) {45		const immer = new Immer(options)4647		const {produce} = immer48		immer.produce = function(...args) {49			return typeof args[1] === "function" && args.length < 350				? produce(...args, listener)51				: produce(...args)52		}5354		return immer55	}5657	describe(`base functionality - ${name}`, () => {58		let baseState59		let origBaseState6061		beforeEach(() => {62			origBaseState = baseState = createBaseState()63		})6465		it("returns the original state when no changes are made", () => {66			const nextState = produce(baseState, s => {67				expect(s.aProp).toBe("hi")68				expect(s.anObject.nested).toMatchObject({yummie: true})69			})70			expect(nextState).toBe(baseState)71		})7273		it("does structural sharing", () => {74			const random = Math.random()75			const nextState = produce(baseState, s => {76				s.aProp = random77			})78			expect(nextState).not.toBe(baseState)79			expect(nextState.aProp).toBe(random)80			expect(nextState.nested).toBe(baseState.nested)81		})8283		it("deep change bubbles up", () => {84			const nextState = produce(baseState, s => {85				s.anObject.nested.yummie = false86			})87			expect(nextState).not.toBe(baseState)88			expect(nextState.anObject).not.toBe(baseState.anObject)89			expect(baseState.anObject.nested.yummie).toBe(true)90			expect(nextState.anObject.nested.yummie).toBe(false)91			expect(nextState.anArray).toBe(baseState.anArray)92		})9394		it("can add props", () => {95			const nextState = produce(baseState, s => {96				s.anObject.cookie = {tasty: true}97			})98			expect(nextState).not.toBe(baseState)99			expect(nextState.anObject).not.toBe(baseState.anObject)100			expect(nextState.anObject.nested).toBe(baseState.anObject.nested)101			expect(nextState.anObject.cookie).toEqual({tasty: true})102		})103104		it("can delete props", () => {105			const nextState = produce(baseState, s => {106				delete s.anObject.nested107			})108			expect(nextState).not.toBe(baseState)109			expect(nextState.anObject).not.toBe(baseState.anObject)110			expect(nextState.anObject.nested).toBe(undefined)111		})112113		// Found by: https://github.com/mweststrate/immer/pull/267114		it("can delete props added in the producer", () => {115			const nextState = produce(baseState, s => {116				s.anObject.test = true117				delete s.anObject.test118			})119			if (useProxies) {120				expect(nextState).not.toBe(baseState)121				expect(nextState).toEqual(baseState)122			} else {123				// The copy is avoided in ES5.124				expect(nextState).toBe(baseState)125			}126		})127128		// Found by: https://github.com/mweststrate/immer/issues/328129		it("can set a property that was just deleted", () => {130			const baseState = {a: 1}131			const nextState = produce(baseState, s => {132				delete s.a133				s.a = 2134			})135			expect(nextState.a).toBe(2)136		})137138		it("can set a property to its original value after deleting it", () => {139			const baseState = {a: {b: 1}}140			const nextState = produce(baseState, s => {141				const a = s.a142				delete s.a143				s.a = a144			})145			if (useProxies) {146				expect(nextState).not.toBe(baseState)147				expect(nextState).toEqual(baseState)148			} else {149				// The copy is avoided in ES5.150				expect(nextState).toBe(baseState)151			}152		})153154		it("can get property descriptors", () => {155			const getDescriptor = Object.getOwnPropertyDescriptor156			const baseState = deepFreeze([{a: 1}])157			produce(baseState, arr => {158				const obj = arr[0]159				const desc = {160					configurable: true,161					enumerable: true,162					...(useProxies && {writable: true})163				}164165				// Known property166				expect(getDescriptor(obj, "a")).toMatchObject(desc)167				expect(getDescriptor(arr, 0)).toMatchObject(desc)168169				// Deleted property170				delete obj.a171				arr.pop()172				expect(getDescriptor(obj, "a")).toBeUndefined()173				expect(getDescriptor(arr, 0)).toBeUndefined()174175				// Unknown property176				expect(getDescriptor(obj, "b")).toBeUndefined()177				expect(getDescriptor(arr, 100)).toBeUndefined()178179				// Added property180				obj.b = 2181				arr[100] = 1182				expect(getDescriptor(obj, "b")).toBeDefined()183				expect(getDescriptor(arr, 100)).toBeDefined()184			})185		})186187		describe("array drafts", () => {188			it("supports Array.isArray()", () => {189				const nextState = produce(baseState, s => {190					expect(Array.isArray(s.anArray)).toBeTruthy()191					s.anArray.push(1)192				})193				expect(Array.isArray(nextState.anArray)).toBeTruthy()194			})195196			it("supports index access", () => {197				const value = baseState.anArray[0]198				const nextState = produce(baseState, s => {199					expect(s.anArray[0]).toBe(value)200				})201				expect(nextState).toBe(baseState)202			})203204			it("supports iteration", () => {205				const base = [206					{id: 1, a: 1},207					{id: 2, a: 1}208				]209				const findById = (collection, id) => {210					for (const item of collection) {211						if (item.id === id) return item212					}213					return null214				}215				const result = produce(base, draft => {216					const obj1 = findById(draft, 1)217					const obj2 = findById(draft, 2)218					obj1.a = 2219					obj2.a = 2220				})221				expect(result[0].a).toEqual(2)222				expect(result[1].a).toEqual(2)223			})224225			it("can assign an index via bracket notation", () => {226				const nextState = produce(baseState, s => {227					s.anArray[3] = true228				})229				expect(nextState).not.toBe(baseState)230				expect(nextState.anArray).not.toBe(baseState.anArray)231				expect(nextState.anArray[3]).toEqual(true)232			})233234			it("can use splice() to both add and remove items", () => {235				const nextState = produce(baseState, s => {236					s.anArray.splice(1, 1, "a", "b")237				})238				expect(nextState.anArray).not.toBe(baseState.anArray)239				expect(nextState.anArray[1]).toBe("a")240				expect(nextState.anArray[2]).toBe("b")241			})242243			it("can truncate via the length property", () => {244				const baseLength = baseState.anArray.length245				const nextState = produce(baseState, s => {246					s.anArray.length = baseLength - 1247				})248				expect(nextState.anArray).not.toBe(baseState.anArray)249				expect(nextState.anArray.length).toBe(baseLength - 1)250			})251252			it("can extend via the length property", () => {253				const baseLength = baseState.anArray.length254				const nextState = produce(baseState, s => {255					s.anArray.length = baseLength + 1256				})257				expect(nextState.anArray).not.toBe(baseState.anArray)258				expect(nextState.anArray.length).toBe(baseLength + 1)259			})260261			// Reported here: https://github.com/mweststrate/immer/issues/116262			it("can pop then push", () => {263				const nextState = produce([1, 2, 3], s => {264					s.pop()265					s.push(100)266				})267				expect(nextState).toEqual([1, 2, 100])268			})269270			it("can be sorted", () => {271				const baseState = [3, 1, 2]272				const nextState = produce(baseState, s => {273					s.sort()274				})275				expect(nextState).not.toBe(baseState)276				expect(nextState).toEqual([1, 2, 3])277			})278279			it("supports modifying nested objects", () => {280				const baseState = [{a: 1}, {}]281				const nextState = produce(baseState, s => {282					s[0].a++283					s[1].a = 0284				})285				expect(nextState).not.toBe(baseState)286				expect(nextState[0].a).toBe(2)287				expect(nextState[1].a).toBe(0)288			})289290			it("never preserves non-numeric properties", () => {291				const baseState = []292				baseState.x = 7293				const nextState = produce(baseState, s => {294					s.push(3)295				})296				expect("x" in nextState).toBeFalsy()297			})298299			if (useProxies && !global.USES_BUILD) {300				it("throws when a non-numeric property is added", () => {301					expect(() => {302						produce([], d => {303							d.x = 3304						})305					}).toThrowErrorMatchingSnapshot()306				})307308				it("throws when a non-numeric property is deleted", () => {309					expect(() => {310						const baseState = []311						baseState.x = 7312						produce(baseState, d => {313							delete d.x314						})315					}).toThrowErrorMatchingSnapshot()316				})317			}318		})319320		describe("map drafts", () => {321			it("supports key access", () => {322				const value = baseState.aMap.get("jedi")323				const nextState = produce(baseState, s => {324					expect(s.aMap.get("jedi")).toEqual(value)325				})326				expect(nextState).toBe(baseState)327			})328329			it("supports key access for non-primitive keys", () => {330				const key = {prop: "val"}331				const base = new Map([[key, {id: 1, a: 1}]])332				const value = base.get(key)333				const nextState = produce(base, s => {334					expect(s.get(key)).toEqual(value)335				})336				expect(nextState).toBe(base)337			})338339			it("supports iteration", () => {340				const base = new Map([341					["first", {id: 1, a: 1}],342					["second", {id: 2, a: 1}]343				])344				const findById = (map, id) => {345					for (const [, item] of map) {346						if (item.id === id) return item347					}348					return null349				}350				const result = produce(base, draft => {351					const obj1 = findById(draft, 1)352					const obj2 = findById(draft, 2)353					obj1.a = 2354					obj2.a = 2355				})356				expect(result).not.toBe(base)357				expect(result.get("first").a).toEqual(2)358				expect(result.get("second").a).toEqual(2)359			})360361			it("supports 'entries'", () => {362				const base = new Map([363					["first", {id: 1, a: 1}],364					["second", {id: 2, a: 1}]365				])366				const findById = (map, id) => {367					for (const [, item] of map.entries()) {368						if (item.id === id) return item369					}370					return null371				}372				const result = produce(base, draft => {373					const obj1 = findById(draft, 1)374					const obj2 = findById(draft, 2)375					obj1.a = 2376					obj2.a = 2377				})378				expect(result).not.toBe(base)379				expect(result.get("first").a).toEqual(2)380				expect(result.get("second").a).toEqual(2)381			})382383			it("supports 'values'", () => {384				const base = new Map([385					["first", {id: 1, a: 1}],386					["second", {id: 2, a: 1}]387				])388				const findById = (map, id) => {389					for (const item of map.values()) {390						if (item.id === id) return item391					}392					return null393				}394				const result = produce(base, draft => {395					const obj1 = findById(draft, 1)396					const obj2 = findById(draft, 2)397					obj1.a = 2398					obj2.a = 2399				})400				expect(result).not.toBe(base)401				expect(result.get("first").a).toEqual(2)402				expect(result.get("second").a).toEqual(2)403			})404405			it("supports 'keys", () => {406				const base = new Map([407					["first", Symbol()],408					["second", Symbol()]409				])410				const result = produce(base, draft => {411					expect([...draft.keys()]).toEqual(["first", "second"])412					draft.set("third", Symbol())413					expect([...draft.keys()]).toEqual(["first", "second", "third"])414				})415			})416417			it("supports forEach", () => {418				const key1 = {prop: "val1"}419				const key2 = {prop: "val2"}420				const base = new Map([421					["first", {id: 1, a: 1}],422					["second", {id: 2, a: 1}],423					[key1, {id: 3, a: 1}],424					[key2, {id: 4, a: 1}]425				])426				const result = produce(base, draft => {427					let sum1 = 0428					draft.forEach(({a}) => {429						sum1 += a430					})431					expect(sum1).toBe(4)432					let sum2 = 0433					draft.get("first").a = 10434					draft.get("second").a = 20435					draft.get(key1).a = 30436					draft.get(key2).a = 40437					draft.forEach(({a}) => {438						sum2 += a439					})440					expect(sum2).toBe(100)441				})442				expect(result).not.toBe(base)443				expect(base.get("first").a).toEqual(1)444				expect(base.get("second").a).toEqual(1)445				expect(base.get(key1).a).toEqual(1)446				expect(base.get(key2).a).toEqual(1)447				expect(result.get("first").a).toEqual(10)448				expect(result.get("second").a).toEqual(20)449				expect(result.get(key1).a).toEqual(30)450				expect(result.get(key2).a).toEqual(40)451			})452453			it("supports forEach mutation", () => {454				const base = new Map([455					["first", {id: 1, a: 1}],456					["second", {id: 2, a: 1}]457				])458				const result = produce(base, draft => {459					draft.forEach(item => {460						item.a = 100461					})462				})463				expect(result).not.toBe(base)464				expect(result.get("first").a).toEqual(100)465				expect(result.get("second").a).toEqual(100)466			})467468			it("can assign by key", () => {469				const nextState = produce(baseState, s => {470					// Map.prototype.set should return the Map itself471					const res = s.aMap.set("force", true)472					if (!global.USES_BUILD) expect(res).toBe(s.aMap[DRAFT_STATE].draft_)473				})474				expect(nextState).not.toBe(baseState)475				expect(nextState.aMap).not.toBe(baseState.aMap)476				expect(nextState.aMap.get("force")).toEqual(true)477			})478479			it("can assign by a non-primitive key", () => {480				const key = {prop: "val"}481				const value = {id: 1, a: 1}482				const base = new Map([[key, value]])483				const nextState = produce(base, s => {484					s.set(key, true)485				})486				expect(nextState).not.toBe(base)487				expect(base.get(key)).toEqual(value)488				expect(nextState.get(key)).toEqual(true)489			})490491			it("state stays the same if the the same item is assigned by key", () => {492				const nextState = produce(baseState, s => {493					s.aMap.set("jediTotal", 42)494				})495				expect(nextState).toBe(baseState)496				expect(nextState.aMap).toBe(baseState.aMap)497			})498499			it("returns 'size'", () => {500				const nextState = produce(baseState, s => {501					s.aMap.set("newKey", true)502					expect(s.aMap.size).toBe(baseState.aMap.size + 1)503				})504				expect(nextState).not.toBe(baseState)505				expect(nextState.aMap).not.toBe(baseState.aMap)506				expect(nextState.aMap.get("newKey")).toEqual(true)507				expect(nextState.aMap.size).toEqual(baseState.aMap.size + 1)508			})509510			it("can use 'delete' to remove items", () => {511				const nextState = produce(baseState, s => {512					expect(s.aMap.has("jedi")).toBe(true)513					expect(s.aMap.delete("jedi")).toBe(true)514					expect(s.aMap.has("jedi")).toBe(false)515				})516				expect(nextState.aMap).not.toBe(baseState.aMap)517				expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)518				expect(baseState.aMap.has("jedi")).toBe(true)519				expect(nextState.aMap.has("jedi")).toBe(false)520			})521522			it("can use 'clear' to remove items", () => {523				const nextState = produce(baseState, s => {524					expect(s.aMap.size).not.toBe(0)525					s.aMap.clear()526					expect(s.aMap.size).toBe(0)527				})528				expect(nextState.aMap).not.toBe(baseState.aMap)529				expect(baseState.aMap.size).not.toBe(0)530				expect(nextState.aMap.size).toBe(0)531			})532533			it("support 'has'", () => {534				const nextState = produce(baseState, s => {535					expect(s.aMap.has("newKey")).toBe(false)536					s.aMap.set("newKey", true)537					expect(s.aMap.has("newKey")).toBe(true)538				})539				expect(nextState).not.toBe(baseState)540				expect(nextState.aMap).not.toBe(baseState.aMap)541				expect(baseState.aMap.has("newKey")).toBe(false)542				expect(nextState.aMap.has("newKey")).toBe(true)543			})544545			it("supports nested maps", () => {546				const base = new Map([["first", new Map([["second", {prop: "test"}]])]])547				const result = produce(base, draft => {548					draft.get("first").get("second").prop = "test1"549				})550				expect(result).not.toBe(base)551				expect(result.get("first")).not.toBe(base.get("first"))552				expect(result.get("first").get("second")).not.toBe(553					base.get("first").get("second")554				)555				expect(base.get("first").get("second").prop).toBe("test")556				expect(result.get("first").get("second").prop).toBe("test1")557			})558559			it("treats void deletes as no-op", () => {560				const base = new Map([["x", 1]])561				const next = produce(base, d => {562					expect(d.delete("y")).toBe(false)563				})564				expect(next).toBe(base)565			})566567			it("revokes map proxies", () => {568				let m569				produce(baseState, s => {570					m = s.aMap571				})572				expect(() => m.get("x")).toThrowErrorMatchingSnapshot()573				expect(() => m.set("x", 3)).toThrowErrorMatchingSnapshot()574			})575576			it("does not draft map keys", () => {577				// anything else would be terribly confusing578				const key = {a: 1}579				const map = new Map([[key, 2]])580				const next = produce(map, d => {581					const dKey = Array.from(d.keys())[0]582					expect(isDraft(dKey)).toBe(false)583					expect(dKey).toBe(key)584					dKey.a += 1585					d.set(dKey, d.get(dKey) + 1)586					d.set(key, d.get(key) + 1)587					expect(d.get(key)).toBe(4)588					expect(key.a).toBe(2)589				})590				const entries = Array.from(next.entries())591				expect(entries).toEqual([[key, 4]])592				expect(entries[0][0]).toBe(key)593				expect(entries[0][0].a).toBe(2)594			})595596			it("does support instanceof Map", () => {597				const map = new Map()598				produce(map, d => {599					expect(d instanceof Map).toBeTruthy()600				})601			})602603			it("handles clear correctly", () => {604				const map = new Map([605					["a", 1],606					["c", 3]607				])608				const next = produce(map, draft => {609					draft.delete("a")610					draft.set("b", 2)611					draft.set("c", 4)612					draft.clear()613				})614				expect(next).toEqual(new Map())615			})616		})617618		describe("set drafts", () => {619			it("supports iteration", () => {620				const base = new Set([621					{id: 1, a: 1},622					{id: 2, a: 1}623				])624				const findById = (set, id) => {625					for (const item of set) {626						if (item.id === id) return item627					}628					return null629				}630				const result = produce(base, draft => {631					const obj1 = findById(draft, 1)632					const obj2 = findById(draft, 2)633					obj1.a = 2634					obj2.a = 2635				})636				expect(result).not.toBe(base)637				expect(base).toEqual(638					new Set([639						{id: 1, a: 1},640						{id: 2, a: 1}641					])642				)643				expect(result).toEqual(644					new Set([645						{id: 1, a: 2},646						{id: 2, a: 2}647					])648				)649			})650651			it("supports 'entries'", () => {652				const base = new Set([653					{id: 1, a: 1},654					{id: 2, a: 1}655				])656				const findById = (set, id) => {657					for (const [item1, item2] of set.entries()) {658						expect(item1).toBe(item2)659						if (item1.id === id) return item1660					}661					return null662				}663				const result = produce(base, draft => {664					const obj1 = findById(draft, 1)665					const obj2 = findById(draft, 2)666					obj1.a = 2667					obj2.a = 2668				})669				expect(result).not.toBe(base)670				expect(base).toEqual(671					new Set([672						{id: 1, a: 1},673						{id: 2, a: 1}674					])675				)676				expect(result).toEqual(677					new Set([678						{id: 1, a: 2},679						{id: 2, a: 2}680					])681				)682			})683684			it("supports 'values'", () => {685				const base = new Set([686					{id: 1, a: 1},687					{id: 2, a: 1}688				])689				const findById = (set, id) => {690					for (const item of set.values()) {691						if (item.id === id) return item692					}693					return null694				}695				const result = produce(base, draft => {696					const obj1 = findById(draft, 1)697					const obj2 = findById(draft, 2)698					obj1.a = 2699					obj2.a = 2700				})701				expect(result).not.toBe(base)702				expect(base).toEqual(703					new Set([704						{id: 1, a: 1},705						{id: 2, a: 1}706					])707				)708				expect(result).toEqual(709					new Set([710						{id: 1, a: 2},711						{id: 2, a: 2}712					])713				)714			})715716			it("supports 'keys'", () => {717				const base = new Set([718					{id: 1, a: 1},719					{id: 2, a: 1}720				])721				const findById = (set, id) => {722					for (const item of set.keys()) {723						if (item.id === id) return item724					}725					return null726				}727				const result = produce(base, draft => {728					const obj1 = findById(draft, 1)729					const obj2 = findById(draft, 2)730					obj1.a = 2731					obj2.a = 2732				})733				expect(result).not.toBe(base)734				expect(base).toEqual(735					new Set([736						{id: 1, a: 1},737						{id: 2, a: 1}738					])739				)740				expect(result).toEqual(741					new Set([742						{id: 1, a: 2},743						{id: 2, a: 2}744					])745				)746			})747748			it("supports forEach with mutation after reads", () => {749				const base = new Set([750					{id: 1, a: 1},751					{id: 2, a: 2}752				])753				const result = produce(base, draft => {754					let sum1 = 0755					draft.forEach(({a}) => {756						sum1 += a757					})758					expect(sum1).toBe(3)759					let sum2 = 0760					draft.forEach(item => {761						item.a += 10762						sum2 += item.a763					})764					expect(sum2).toBe(23)765				})766				expect(result).not.toBe(base)767				expect(base).toEqual(768					new Set([769						{id: 1, a: 1},770						{id: 2, a: 2}771					])772				)773				expect(result).toEqual(774					new Set([775						{id: 1, a: 11},776						{id: 2, a: 12}777					])778				)779			})780781			it("state stays the same if the same item is added", () => {782				const nextState = produce(baseState, s => {783					s.aSet.add("Luke")784				})785				expect(nextState).toBe(baseState)786				expect(nextState.aSet).toBe(baseState.aSet)787			})788789			it("can add new items", () => {790				const nextState = produce(baseState, s => {791					// Set.prototype.set should return the Set itself792					const res = s.aSet.add("force")793					if (!global.USES_BUILD) expect(res).toBe(s.aSet[DRAFT_STATE].draft_)794				})795				expect(nextState).not.toBe(baseState)796				expect(nextState.aSet).not.toBe(baseState.aSet)797				expect(baseState.aSet.has("force")).toBe(false)798				expect(nextState.aSet.has("force")).toBe(true)799			})800801			it("returns 'size'", () => {802				const nextState = produce(baseState, s => {803					s.aSet.add("newKey")804					expect(s.aSet.size).toBe(baseState.aSet.size + 1)805				})806				expect(nextState).not.toBe(baseState)807				expect(nextState.aSet).not.toBe(baseState.aSet)808				expect(nextState.aSet.has("newKey")).toBe(true)809				expect(nextState.aSet.size).toEqual(baseState.aSet.size + 1)810			})811812			it("can use 'delete' to remove items", () => {813				const nextState = produce(baseState, s => {814					expect(s.aSet.has("Luke")).toBe(true)815					expect(s.aSet.delete("Luke")).toBe(true)816					expect(s.aSet.delete("Luke")).toBe(false)817					expect(s.aSet.has("Luke")).toBe(false)818				})819				expect(nextState.aSet).not.toBe(baseState.aSet)820				expect(baseState.aSet.has("Luke")).toBe(true)821				expect(nextState.aSet.has("Luke")).toBe(false)822				expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)823			})824825			it("can use 'clear' to remove items", () => {826				const nextState = produce(baseState, s => {827					expect(s.aSet.size).not.toBe(0)828					s.aSet.clear()829					expect(s.aSet.size).toBe(0)830				})831				expect(nextState.aSet).not.toBe(baseState.aSet)832				expect(baseState.aSet.size).not.toBe(0)833				expect(nextState.aSet.size).toBe(0)834			})835836			it("supports 'has'", () => {837				const nextState = produce(baseState, s => {838					expect(s.aSet.has("newKey")).toBe(false)839					s.aSet.add("newKey")840					expect(s.aSet.has("newKey")).toBe(true)841				})842				expect(nextState).not.toBe(baseState)843				expect(nextState.aSet).not.toBe(baseState.aSet)844				expect(baseState.aSet.has("newKey")).toBe(false)845				expect(nextState.aSet.has("newKey")).toBe(true)846			})847848			it("supports nested sets", () => {849				const base = new Set([new Set(["Serenity"])])850				const result = produce(base, draft => {851					draft.forEach(nestedItem => nestedItem.add("Firefly"))852				})853				expect(result).not.toBe(base)854				expect(base).toEqual(new Set([new Set(["Serenity"])]))855				expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))856			})857858			it("supports has / delete on elements from the original", () => {859				const obj = {}860				const set = new Set([obj])861				const next = produce(set, d => {862					expect(d.has(obj)).toBe(true)863					d.add(3)864					expect(d.has(obj)).toBe(true)865					d.delete(obj)866					expect(d.has(obj)).toBe(false)867				})868				expect(next).toEqual(new Set([3]))869			})870871			it("revokes sets", () => {872				let m873				produce(baseState, s => {874					m = s.aSet875				})876				expect(() => m.has("x")).toThrowErrorMatchingSnapshot()877				expect(() => m.add("x")).toThrowErrorMatchingSnapshot()878			})879880			it("does support instanceof Set", () => {881				const set = new Set()882				produce(set, d => {883					expect(d instanceof Set).toBeTruthy()884				})885			})886		})887888		it("supports `immerable` symbol on constructor", () => {889			class One {}890			One[immerable] = true891			const baseState = new One()892			const nextState = produce(baseState, draft => {893				expect(draft).not.toBe(baseState)894				draft.foo = true895			})896			expect(nextState).not.toBe(baseState)897			expect(nextState.foo).toBeTruthy()898		})899900		it("preserves symbol properties", () => {901			const test = Symbol("test")902			const baseState = {[test]: true}903			const nextState = produce(baseState, s => {904				expect(s[test]).toBeTruthy()905				s.foo = true906			})907			expect(nextState).toEqual({908				[test]: true,909				foo: true910			})911		})912913		if (!global.USES_BUILD)914			it("preserves non-enumerable properties", () => {915				const baseState = {}916				// Non-enumerable object property917				Object.defineProperty(baseState, "foo", {918					value: {a: 1},919					enumerable: false920				})921				// Non-enumerable primitive property922				Object.defineProperty(baseState, "bar", {923					value: 1,924					enumerable: false925				})926				const nextState = produce(baseState, s => {927					expect(s.foo).toBeTruthy()928					expect(isEnumerable(s, "foo")).toBeFalsy()929					s.bar++930					expect(isEnumerable(s, "foo")).toBeFalsy()931					s.foo.a++932					expect(isEnumerable(s, "foo")).toBeFalsy()933				})934				expect(nextState.foo).toBeTruthy()935				expect(isEnumerable(nextState, "foo")).toBeFalsy()936			})937938		it("can work with own computed props", () => {939			const baseState = {940				x: 1,941				get y() {942					return this.x943				},944				set y(v) {945					this.x = v946				}947			}948949			const nextState = produce(baseState, d => {950				expect(d.y).toBe(1)951				d.x = 2952				expect(d.x).toBe(2)953				expect(d.y).toBe(1) // this has been copied!954				d.y = 3955				expect(d.x).toBe(2)956			})957			expect(baseState.x).toBe(1)958			expect(baseState.y).toBe(1)959960			expect(nextState.x).toBe(2)961			expect(nextState.y).toBe(3)962			if (!autoFreeze) {963				nextState.y = 4 // decoupled now!964				expect(nextState.y).toBe(4)965				expect(nextState.x).toBe(2)966				expect(Object.getOwnPropertyDescriptor(nextState, "y").value).toBe(4)967			}968		})969970		it("can work with class with computed props", () => {971			class State {972				[immerable] = true973974				x = 1975976				set y(v) {977					this.x = v978				}979980				get y() {981					return this.x982				}983			}984985			const baseState = new State()986987			const nextState = produce(baseState, d => {988				expect(d.y).toBe(1)989				d.y = 2990				expect(d.x).toBe(2)991				expect(d.y).toBe(2)992				expect(Object.getOwnPropertyDescriptor(d, "y")).toBeUndefined()993			})994			expect(baseState.x).toBe(1)995			expect(baseState.y).toBe(1)996997			expect(nextState.x).toBe(2)998			expect(nextState.y).toBe(2)999			expect(Object.getOwnPropertyDescriptor(nextState, "y")).toBeUndefined()1000		})10011002		it("allows inherited computed properties", () => {1003			const proto = {}1004			Object.defineProperty(proto, "foo", {1005				get() {1006					return this.bar1007				},1008				set(val) {1009					this.bar = val1010				}1011			})1012			proto[immerable] = true1013			const baseState = Object.create(proto)1014			produce(baseState, s => {1015				expect(s.bar).toBeUndefined()1016				s.foo = {}1017				expect(s.bar).toBeDefined()1018				expect(s.foo).toBe(s.bar)1019			})1020		})10211022		it("optimization: does not visit properties of new data structures if autofreeze is disabled and no drafts are unfinalized", () => {1023			const newData = {}1024			Object.defineProperty(newData, "x", {1025				enumerable: true,1026				get() {1027					throw new Error("visited!")1028				}1029			})10301031			const run = () =>1032				produce({}, d => {1033					d.data = newData1034				})1035			if (autoFreeze) {1036				expect(run).toThrow("visited!")1037			} else {1038				expect(run).not.toThrow("visited!")1039			}1040		})10411042		it("same optimization doesn't cause draft from nested producers to be unfinished", () => {1043			const base = {1044				y: 1,1045				child: {1046					x: 11047				}1048			}1049			const wrap = produce(draft => {1050				return {1051					wrapped: draft1052				}1053			})10541055			const res = produce(base, draft => {1056				draft.y++1057				draft.child = wrap(draft.child)1058				draft.child.wrapped.x++1059			})10601061			expect(res).toEqual({1062				y: 2,1063				child: {wrapped: {x: 2}}1064			})1065		})10661067		it("supports a base state with multiple references to an object", () => {1068			const obj = {}1069			const res = produce({a: obj, b: obj}, d => {1070				// Two drafts are created for each occurrence of an object in the base state.1071				expect(d.a).not.toBe(d.b)1072				d.a.z = true1073				expect(d.b.z).toBeUndefined()1074			})1075			expect(res.b).toBe(obj)1076			expect(res.a).not.toBe(res.b)1077			expect(res.a.z).toBeTruthy()1078		})10791080		// NOTE: Except the root draft.1081		it("supports multiple references to any modified draft", () => {1082			const next = produce({a: {b: 1}}, d => {1083				d.a.b++1084				d.b = d.a1085			})1086			expect(next.a).toBe(next.b)1087		})10881089		it("can rename nested objects (no changes)", () => {1090			const nextState = produce({obj: {}}, s => {1091				s.foo = s.obj1092				delete s.obj1093			})1094			expect(nextState).toEqual({foo: {}})1095		})10961097		// Very similar to the test before, but the reused object has one1098		// property changed, one added, and one removed.1099		it("can rename nested objects (with changes)", () => {1100			const nextState = produce({obj: {a: 1, b: 1}}, s => {1101				s.obj.a = true // change1102				delete s.obj.b // delete1103				s.obj.c = true // add11041105				s.foo = s.obj1106				delete s.obj1107			})1108			expect(nextState).toEqual({foo: {a: true, c: true}})1109		})11101111		it("can nest a draft in a new object (no changes)", () => {1112			const baseState = {obj: {}}1113			const nextState = produce(baseState, s => {1114				s.foo = {bar: s.obj}1115				delete s.obj1116			})1117			expect(nextState.foo.bar).toBe(baseState.obj)1118		})11191120		it("can nest a modified draft in a new object", () => {1121			const nextState = produce({obj: {a: 1, b: 1}}, s => {1122				s.obj.a = true // change1123				delete s.obj.b // delete1124				s.obj.c = true // add11251126				s.foo = {bar: s.obj}1127				delete s.obj1128			})1129			expect(nextState).toEqual({foo: {bar: {a: true, c: true}}})1130		})11311132		it("supports assigning undefined to an existing property", () => {1133			const nextState = produce(baseState, s => {1134				s.aProp = undefined1135			})1136			expect(nextState).not.toBe(baseState)1137			expect(nextState.aProp).toBe(undefined)1138		})11391140		it("supports assigning undefined to a new property", () => {1141			const baseState = {}1142			const nextState = produce(baseState, s => {1143				s.aProp = undefined1144			})1145			expect(nextState).not.toBe(baseState)1146			expect(nextState.aProp).toBe(undefined)1147		})11481149		// NOTE: ES5 drafts only protect existing properties when revoked.1150		if (!isProd)1151			it("revokes the draft once produce returns", () => {1152				const expectRevoked = (fn, shouldThrow = true) => {1153					if (shouldThrow) expect(fn).toThrowErrorMatchingSnapshot()1154					else expect(fn).not.toThrow()1155				}11561157				// Test object drafts:1158				let draft1159				produce({a: 1, b: 1}, s => {1160					draft = s1161					delete s.b1162				})11631164				// Access known property on object draft.1165				expectRevoked(() => {1166					draft.a1167				})11681169				// Assign known property on object draft.1170				expectRevoked(() => {1171					draft.a = true1172				})11731174				// Access unknown property on object draft.1175				expectRevoked(() => {1176					draft.z1177				}, useProxies)11781179				// Assign unknown property on object draft.1180				expectRevoked(() => {1181					draft.z = true1182				}, useProxies)11831184				// Test array drafts:1185				produce([1, 2], s => {1186					draft = s1187					s.pop()1188				})11891190				// Access known index of an array draft.1191				expectRevoked(() => {1192					draft[0]1193				})11941195				// Assign known index of an array draft.1196				expectRevoked(() => {1197					draft[0] = true1198				})11991200				// Access unknown index of an array draft.1201				expectRevoked(() => {1202					draft[1]1203				}, useProxies)12041205				// Assign unknown index of an array draft.1206				expectRevoked(() => {1207					draft[1] = true1208				}, useProxies)1209			})12101211		it("can access a child draft that was created before the draft was modified", () => {1212			produce({a: {}}, s => {1213				const before = s.a1214				s.b = 11215				expect(s.a).toBe(before)1216			})1217		})12181219		it("should reflect all changes made in the draft immediately", () => {1220			produce(baseState, draft => {1221				draft.anArray[0] = 51222				draft.anArray.unshift("test")1223				if (!global.USES_BUILD)1224					expect(enumerableOnly(draft.anArray)).toEqual([1225						"test",1226						5,1227						2,1228						{c: 3},1229						11230					])1231				draft.stuffz = "coffee"1232				expect(draft.stuffz).toBe("coffee")1233			})1234		})12351236		if (useProxies)1237			it("throws when Object.defineProperty() is used on drafts", () => {1238				expect(() => {1239					produce({}, draft => {1240						Object.defineProperty(draft, "xx", {1241							enumerable: true,1242							writeable: true,1243							value: 21244						})1245					})1246				}).toThrowErrorMatchingSnapshot()1247			})12481249		it("should handle constructor correctly", () => {1250			const baseState = {1251				arr: new Array(),1252				obj: new Object()1253			}1254			const result = produce(baseState, draft => {1255				draft.arrConstructed = draft.arr.constructor(1)1256				draft.objConstructed = draft.obj.constructor(1)1257			})1258			expect(result.arrConstructed).toEqual(new Array().constructor(1))1259			expect(result.objConstructed).toEqual(new Object().constructor(1))1260		})12611262		it("should handle equality correctly - 1", () => {1263			const baseState = {1264				y: 3 / 0,1265				z: NaN1266			}1267			const nextState = produce(baseState, draft => {1268				draft.y = 4 / 01269				draft.z = NaN1270			})1271			expect(nextState).toBe(baseState)1272		})12731274		it("should handle equality correctly - 2", () => {1275			const baseState = {1276				x: -01277			}1278			const nextState = produce(baseState, draft => {1279				draft.x = +01280			})1281			// 0 === -0 // true1282			// Object.is(0, -0) // false1283			//1284			// MWE:1285			// Immer preserves the difference between -0 and +0,1286			// so a new state is created.1287			// This isn't defined anywhere explicitly, so could be changed1288			// in the future to follow === behavior, rather than Object.is.1289			// But I think this is fine as is.1290			expect(nextState).not.toBe(baseState)1291			expect(nextState.x).toBe(-0)1292			expect(nextState.x).not.toBe(+0)1293			// however, toEqual treats -0 === +0 (which is true!)1294			expect(nextState).toEqual(baseState)1295		})12961297		it("should handle equality correctly - 3", () => {1298			const baseState = {1299				x: "s1",1300				y: 1,1301				z: NaN1302			}1303			const nextState = produce(baseState, draft => {1304				draft.x = "s2"1305				draft.y = 11306				draft.z = NaN1307				if (!isProd) {1308					expect(draft[DRAFT_STATE].assigned_.x).toBe(true)1309					expect(draft[DRAFT_STATE].assigned_.y).toBe(undefined)1310					expect(draft[DRAFT_STATE].assigned_.z).toBe(undefined)1311				}1312			})1313			expect(nextState.x).toBe("s2")1314		})13151316		// AKA: recursive produce calls1317		describe("nested producers", () => {1318			describe("when base state is not a draft", () => {1319				// This test ensures the global state used to manage proxies is1320				// never left in a corrupted state by a nested `produce` call.1321				it("never affects its parent producer implicitly", () => {1322					const base = {obj: {a: 1}}1323					const next = produce(base, draft => {1324						// Notice how `base.obj` is passed, not `draft.obj`1325						const obj2 = produce(base.obj, draft2 => {1326							draft2.a = 01327						})1328						expect(obj2.a).toBe(0)1329						expect(draft.obj.a).toBe(1) // effects should not be visible outside1330					})1331					expect(next).toBe(base)1332				})1333			})13341335			describe("when base state is a draft", () => {1336				it("always wraps the draft in a new draft", () => {1337					produce({}, parent => {1338						produce(parent, child => {1339							expect(child).not.toBe(parent)1340							expect(isDraft(child)).toBeTruthy()1341							expect(original(child)).toBe(parent)1342						})1343					})1344				})13451346				// Reported by: https://github.com/mweststrate/immer/issues/3431347				it("ensures each property is drafted", () => {1348					produce({a: {}, b: {}}, parent => {1349						parent.a // Access "a" but not "b"1350						produce(parent, child => {1351							child.c = 11352							expect(isDraft(child.a)).toBeTruthy()1353							expect(isDraft(child.b)).toBeTruthy()1354						})1355					})1356				})13571358				it("preserves any pending changes", () => {1359					produce({a: 1, b: 1, d: 1}, parent => {1360						parent.b = 21361						parent.c = 21362						delete parent.d1363						produce(parent, child => {1364							expect(child.a).toBe(1) // unchanged1365							expect(child.b).toBe(2) // changed1366							expect(child.c).toBe(2) // added1367							expect(child.d).toBeUndefined() // deleted1368						})1369					})1370				})1371			})13721373			describe("when base state contains a draft", () => {1374				it("wraps unowned draft with its own draft", () => {1375					produce({a: {}}, parent => {1376						produce({a: parent.a}, child => {1377							expect(child.a).not.toBe(parent.a)1378							expect(isDraft(child.a)).toBeTruthy()1379							expect(original(child.a)).toBe(parent.a)1380						})1381					})1382				})13831384				it("returns unowned draft if no changes were made", () => {1385					produce({a: {}}, parent => {1386						const result = produce({a: parent.a}, () => {})1387						expect(result.a).toBe(parent.a)1388					})1389				})13901391				it("clones the unowned draft when changes are made", () => {1392					produce({a: {}}, parent => {1393						const result = produce({a: parent.a}, child => {1394							child.a.b = 11395						})1396						expect(result.a).not.toBe(parent.a)1397						expect(result.a.b).toBe(1)1398						expect("b" in parent.a).toBeFalsy()1399					})1400				})14011402				// We cannot auto-freeze the result of a nested producer,1403				// because it may contain a draft from a parent producer.1404				it("never auto-freezes the result", () => {1405					produce({a: {}}, parent => {1406						const r = produce({a: parent.a}, child => {1407							child.b = 1 // Ensure a copy is returned.1408						})1409						expect(Object.isFrozen(r)).toBeFalsy()1410					})1411				})1412			})14131414			// "Upvalues" are variables from a parent scope.1415			it("does not finalize upvalue drafts", () => {1416				produce({a: {}, b: {}}, parent => {1417					expect(produce({}, () => parent)).toBe(parent)1418					parent.x // Ensure proxy not revoked.14191420					expect(produce({}, () => [parent])[0]).toBe(parent)1421					parent.x // Ensure proxy not revoked.14221423					expect(produce({}, () => parent.a)).toBe(parent.a)1424					parent.a.x // Ensure proxy not revoked.14251426					// Modified parent test1427					parent.c = 11428					expect(produce({}, () => [parent.b])[0]).toBe(parent.b)1429					parent.b.x // Ensure proxy not revoked.1430				})1431			})14321433			it("works with interweaved Immer instances", () => {1434				const options = {useProxies, autoFreeze}1435				const one = createPatchedImmer(options)1436				const two = createPatchedImmer(options)14371438				const base = {}1439				const result = one.produce(base, s1 =>1440					two.produce({s1}, s2 => {1441						expect(original(s2.s1)).toBe(s1)1442						s2.n = 11443						s2.s1 = one.produce({s2}, s3 => {1444							expect(original(s3.s2)).toBe(s2)1445							expect(original(s3.s2.s1)).toBe(s2.s1)1446							return s3.s2.s11447						})1448					})1449				)1450				expect(result.n).toBe(1)1451				expect(result.s1).toBe(base)1452			})1453		})14541455		if (useProxies)1456			it("throws when Object.setPrototypeOf() is used on a draft", () => {1457				produce({}, draft => {1458					expect(() =>1459						Object.setPrototypeOf(draft, Array)1460					).toThrowErrorMatchingSnapshot()1461				})1462			})14631464		it("supports the 'in' operator", () => {1465			produce(baseState, draft => {1466				// Known property1467				expect("anArray" in draft).toBe(true)1468				expect(Reflect.has(draft, "anArray")).toBe(true)14691470				// Unknown property1471				expect("bla" in draft).toBe(false)1472				expect(Reflect.has(draft, "bla")).toBe(false)14731474				// Known index1475				expect(0 in draft.anArray).toBe(true)1476				expect("0" in draft.anArray).toBe(true)1477				expect(Reflect.has(draft.anArray, 0)).toBe(true)1478				expect(Reflect.has(draft.anArray, "0")).toBe(true)14791480				// Unknown index1481				expect(17 in draft.anArray).toBe(false)1482				expect("17" in draft.anArray).toBe(false)1483				expect(Reflect.has(draft.anArray, 17)).toBe(false)1484				expect(Reflect.has(draft.anArray, "17")).toBe(false)1485			})1486		})14871488		it("'this' should not be bound anymore - 1", () => {1489			const base = {x: 3}1490			const next1 = produce(base, function() {1491				expect(this).toBe(undefined)1492			})1493		})14941495		it("'this' should not be bound anymore - 2", () => {1496			const incrementor = produce(function() {1497				expect(this).toBe(undefined)1498			})1499			incrementor()1500		})15011502		it("should be possible to use dynamic bound this", () => {1503			const world = {1504				counter: {count: 1},1505				inc: produce(function(draft) {1506					expect(this).toBe(world)1507					draft.counter.count = this.counter.count + 11508				})1509			}15101511			expect(world.inc(world).counter.count).toBe(2)1512		})15131514		it("doesnt recurse into frozen structures if external data is frozen", () => {1515			const frozen = {}1516			Object.defineProperty(frozen, "x", {1517				get() {1518					throw "oops"1519				},1520				enumerable: true,1521				configurable: true1522			})1523			Object.freeze(frozen)15241525			expect(() => {1526				produce({}, d => {1527					d.x = frozen1528				})1529			}).not.toThrow()1530		})15311532		// See here: https://github.com/mweststrate/immer/issues/891533		it("supports the spread operator", () => {1534			const base = {foo: {x: 0, y: 0}, bar: [0, 0]}1535			const result = produce(base, draft => {1536				draft.foo = {x: 1, ...draft.foo, y: 1}1537				draft.bar = [1, ...draft.bar, 1]1538			})1539			expect(result).toEqual({1540				foo: {x: 0, y: 1},1541				bar: [1, 0, 0, 1]1542			})1543		})15441545		it("processes with lodash.set", () => {1546			const base = [{id: 1, a: 1}]1547			const result = produce(base, draft => {1548				lodash.set(draft, "[0].a", 2)1549			})1550			expect(base[0].a).toEqual(1)1551			expect(result[0].a).toEqual(2)1552		})15531554		it("processes with lodash.find", () => {1555			const base = [{id: 1, a: 1}]1556			const result = produce(base, draft => {1557				const obj1 = lodash.find(draft, {id: 1})1558				lodash.set(obj1, "a", 2)1559			})1560			expect(base[0].a).toEqual(1)1561			expect(result[0].a).toEqual(2)1562		})15631564		it("does not draft external data", () => {1565			const externalData = {x: 3}1566			const base = {}1567			const next = produce(base, draft => {1568				// potentially, we *could* draft external data automatically, but only if those statements are not switched...1569				draft.y = externalData1570				draft.y.x += 11571				externalData.x += 11572			})1573			expect(next).toEqual({y: {x: 5}})1574			expect(externalData.x).toBe(5)1575			expect(next.y).toBe(externalData)1576		})15771578		it("does not create new state unnecessary, #491", () => {1579			const a = {highlight: true}1580			const next1 = produce(a, draft => {1581				draft.highlight = false1582				draft.highlight = true1583			})1584			// See explanation in issue1585			expect(next1).not.toBe(a)15861587			const next2 = produce(a, draft => {1588				draft.highlight = true1589			})1590			expect(next2).toBe(a)1591		})15921593		autoFreeze &&1594			test("issue #462 - frozen", () => {1595				var origin = {1596					a: {1597						value: "no"1598					},1599					b: {1600						value: "no"1601					}1602				}1603				const next = produce(origin, draft => {1604					draft.a.value = "im"1605				})1606				expect(() => {1607					origin.b.value = "yes"1608				}).toThrowError(1609					"Cannot assign to read only property 'value' of object '#<Object>'"1610				)1611				expect(() => {1612					next.b.value = "yes"1613				}).toThrowError(1614					"Cannot assign to read only property 'value' of object '#<Object>'"1615				) // should throw!1616			})16171618		autoFreeze &&1619			test("issue #469, state not frozen", () => {1620				const project = produce(1621					{1622						id: 1,1623						tracks: [{id: 1}]1624					},1625					() => {}1626				)16271628				expect(() => {1629					project.id = 2 // Does not throw error1630				}).toThrowError("Cannot assign to read only property 'id'")16311632				expect(() => {1633					Object.assign(project, {id: 2}) // Uncaught TypeError: Cannot assign to read only property 'id' of object '#<Object>'1634				}).toThrowError("Cannot assign to read only property 'id'")1635			})16361637		describe("recipe functions", () => {1638			it("can return a new object", () => {1639				const base = {x: 3}1640				const res = produce(base, d => {1641					return {x: d.x + 1}1642				})1643				expect(res).not.toBe(base)1644				expect(res).toEqual({x: 4})1645			})16461647			it("can return the draft", () => {1648				const base = {x: 3}1649				const res = produce(base, d => {1650					d.x = 41651					return d1652				})1653				expect(res).not.toBe(base)1654				expect(res).toEqual({x: 4})1655			})16561657			it("can return an unmodified child draft", () => {1658				const base = {a: {}}1659				const res = produce(base, d => {1660					return d.a1661				})1662				expect(res).toBe(base.a)1663			})16641665			// TODO: Avoid throwing if only the child draft was modified.1666			it("cannot return a modified child draft", () => {1667				const base = {a: {}}1668				expect(() => {1669					produce(base, d => {1670						d.a.b = 11671						return d.a1672					})1673				}).toThrowErrorMatchingSnapshot()1674			})16751676			it("can return a frozen object", () => {1677				const res = deepFreeze([{x: 3}])1678				expect(produce({}, () => res)).toBe(res)1679			})16801681			it("can return an object with two references to another object", () => {1682				const next = produce({}, d => {1683					const obj = {}1684					return {obj, arr: [obj]}1685				})1686				expect(next.obj).toBe(next.arr[0])1687			})16881689			it("can return an object with two references to an unmodified draft", () => {1690				const base = {a: {}}1691				const next = produce(base, d => {1692					return [d.a, d.a]1693				})1694				expect(next[0]).toBe(base.a)1695				expect(next[0]).toBe(next[1])1696			})16971698			it("cannot return an object that references itself", () => {1699				const res = {}1700				res.self = res1701				expect(() => {1702					produce(res, () => res.self)1703				}).toThrowErrorMatchingSnapshot()1704			})1705		})17061707		describe("async recipe function", () => {1708			it("can modify the draft", () => {1709				const base = {a: 0, b: 0}1710				return produce(base, async d => {1711					d.a = 11712					await Promise.resolve()1713					d.b = 11714				}).then(res => {1715					expect(res).not.toBe(base)1716					expect(res).toEqual({a: 1, b: 1})1717				})1718			})17191720			it("works with rejected promises", () => {1721				let draft1722				const base = {a: 0, b: 0}1723				const err = new Error("passed")1724				return produce(base, d => {1725					draft = d1726					draft.b = 11727					return Promise.reject(err)1728				}).then(1729					() => {1730						throw "failed"1731					},1732					e => {1733						expect(e).toBe(err)1734						if (!isProd) expect(() => draft.a).toThrowErrorMatchingSnapshot()1735					}1736				)1737			})17381739			it("supports recursive produce calls after await", () => {1740				const base = {obj: {k: 1}}1741				return produce(base, d => {1742					const obj = d.obj1743					delete d.obj1744					return Promise.resolve().then(() => {1745						d.a = produce({}, d => {1746							d.b = obj // Assign a draft owned by the parent scope.1747						})17481749						// Auto-freezing is prevented when an unowned draft exists.1750						expect(Object.isFrozen(d.a)).toBeFalsy()17511752						// Ensure `obj` is not revoked.1753						obj.c = 11754					})1755				}).then(res => {1756					expect(res).not.toBe(base)1757					expect(res).toEqual({1758						a: {b: {k: 1, c: 1}}1759					})1760				})1761			})17621763			it("works with patches", () =>1764				produceWithPatches({a: 0}, async d => {1765					await Promise.resolve()1766					d.a = 11767				}).then(([nextState, patches, inversePathes]) => {1768					expect(nextState).toEqual({a: 1})1769					expect(patches).toEqual([{op: "replace", path: ["a"], value: 1}])1770					expect(inversePathes).toEqual([1771						{op: "replace", path: ["a"], value: 0}1772					])1773				}))1774		})17751776		it("throws when the draft is modified and another object is returned", () => {1777			const base = {x: 3}1778			expect(() => {1779				produce(base, draft => {1780					draft.x = 41781					return {x: 5}1782				})1783			}).toThrowErrorMatchingSnapshot()1784		})17851786		it("should fix #117 - 1", () => {1787			const reducer = (state, action) =>1788				produce(state, draft => {1789					switch (action.type) {1790						case "SET_STARTING_DOTS":1791							return draft.availableStartingDots.map(a => a)1792						default:1793							break1794					}1795				})1796			const base = {1797				availableStartingDots: [1798					{dots: 4, count: 1},1799					{dots: 3, count: 2},1800					{dots: 2, count: 3},1801					{dots: 1, count: 4}1802				]1803			}1804			const next = reducer(base, {type: "SET_STARTING_DOTS"})1805			expect(next).toEqual(base.availableStartingDots)1806			expect(next).not.toBe(base.availableStartingDots)1807		})18081809		it("should fix #117 - 2", () => {1810			const reducer = (state, action) =>1811				produce(state, draft => {1812					switch (action.type) {1813						case "SET_STARTING_DOTS":1814							return {1815								dots: draft.availableStartingDots.map(a => a)1816							}1817						default:1818							break1819					}1820				})1821			const base = {1822				availableStartingDots: [1823					{dots: 4, count: 1},1824					{dots: 3, count: 2},1825					{dots: 2, count: 3},1826					{dots: 1, count: 4}1827				]1828			}1829			const next = reducer(base, {type: "SET_STARTING_DOTS"})1830			expect(next).toEqual({dots: base.availableStartingDots})1831		})18321833		it("cannot always detect noop assignments - 0", () => {1834			const baseState = {x: {y: 3}}1835			const nextState = produce(baseState, d => {1836				const a = d.x1837				d.x = a1838			})1839			expect(nextState).toBe(baseState)1840		})18411842		it("cannot always detect noop assignments - 1", () => {1843			const baseState = {x: {y: 3}}1844			const nextState = produce(baseState, d => {1845				const a = d.x1846				d.x = 41847				d.x = a1848			})1849			// Ideally, this should actually be the same instances1850			// but this would be pretty expensive to detect,1851			// so we don't atm1852			expect(nextState).not.toBe(baseState)1853		})18541855		it("cannot always detect noop assignments - 2", () => {1856			const baseState = {x: {y: 3}}1857			const nextState = produce(baseState, d => {1858				const a = d.x1859				const stuff = a.y + 31860				d.x = 41861				d.x = a1862			})1863			// Ideally, this should actually be the same instances1864			// but this would be pretty expensive to detect,1865			// so we don't atm1866			expect(nextState).not.toBe(baseState)1867		})18681869		it("cannot always detect noop assignments - 3", () => {1870			const baseState = {x: 3}1871			const nextState = produce(baseState, d => {1872				d.x = 31873			})1874			expect(nextState).toBe(baseState)1875		})18761877		it("cannot always detect noop assignments - 4", () => {1878			const baseState = {x: 3}1879			const nextState = produce(baseState, d => {1880				d.x = 41881				d.x = 31882			})1883			// Ideally, this should actually be the same instances1884			// but this would be pretty expensive to detect,1885			// so we don't atm1886			expect(nextState).not.toBe(baseState)1887		})18881889		it("cannot always detect noop assignments - 4", () => {1890			const baseState = {}1891			const [nextState, patches] = produceWithPatches(baseState, d => {1892				d.x = 41893				delete d.x1894			})1895			expect(nextState).toEqual({})1896			expect(patches).toEqual([])1897			// This differs between ES5 and proxy, and ES5 does it better :(1898			if (useProxies) expect(nextState).not.toBe(baseState)1899			else expect(nextState).toBe(baseState)1900		})19011902		it("cannot produce undefined by returning undefined", () => {1903			const base = 31904			expect(produce(base, () => 4)).toBe(4)1905			expect(produce(base, () => null)).toBe(null)1906			expect(produce(base, () => undefined)).toBe(3)1907			expect(produce(base, () => {})).toBe(3)1908			expect(produce(base, () => nothing)).toBe(undefined)19091910			expect(produce({}, () => undefined)).toEqual({})1911			expect(produce({}, () => nothing)).toBe(undefined)1912			expect(produce(3, () => nothing)).toBe(undefined)19131914			expect(produce(() => undefined)({})).toEqual({})1915			expect(produce(() => nothing)({})).toBe(undefined)1916			expect(produce(() => nothing)(3)).toBe(undefined)1917		})19181919		describe("base state type", () => {1920			if (!global.USES_BUILD) testObjectTypes(produce)1921			testLiteralTypes(produce)1922		})19231924		afterEach(() => {1925			expect(baseState).toBe(origBaseState)1926			expect(baseState).toEqual(createBaseState())1927		})19281929		class Foo {}1930		function createBaseState() {1931			const data = {1932				anInstance: new Foo(),1933				anArray: [3, 2, {c: 3}, 1],1934				aMap: new Map([1935					["jedi", {name: "Luke", skill: 10}],1936					["jediTotal", 42],1937					["force", "these aren't the droids you're looking for"]1938				]),1939				aSet: new Set([1940					"Luke",1941					42,1942					{1943						jedi: "Yoda"1944					}1945				]),1946				aProp: "hi",1947				anObject: {1948					nested: {1949						yummie: true1950					},1951					coffee: false1952				}1953			}1954			return autoFreeze ? deepFreeze(data) : data1955		}1956	})19571958	it(`works with spread #524 - ${name}`, () => {1959		const state = {1960			level1: {1961				level2: {1962					level3: "data"1963				}1964			}1965		}19661967		const nextState = produce(state, draft => {1968			return {...draft}1969		})1970		const nextState1 = produce(state, draft => {1971			const newLevel1 = produce(draft.level1, level1Draft => {1972				return {...level1Draft}1973			})1974			draft.level1 = newLevel11975		})19761977		const nextState2 = produce(state, draft => {1978			const newLevel1 = produce(draft.level1, level1Draft => {1979				return {...level1Draft}1980			})1981			return {1982				level1: newLevel11983			}1984		})19851986		const nextState3 = produce(state, draft => {1987			const newLevel1 = produce(draft.level1, level1Draft => {1988				return Object.assign({}, level1Draft)1989			})1990			return Object.assign(draft, {1991				level1: newLevel11992			})1993		})19941995		const expected = {level1: {level2: {level3: "data"}}}1996		expect(nextState1).toEqual(expected)1997		expect(nextState2).toEqual(expected)1998		expect(nextState3).toEqual(expected)1999	})2000

The first 2,000 of 2,500 lines.