Skip to content
Myr

map-set.js

This file

Path

__tests__/map-set.js

484 lines · 10.9 KiB · JavaScript

Last changed by

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58

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, isEnumerable, DRAFT_STATE} from "../src/utils/common"1314enableMapSet()15enablePatches()1617vi.setConfig({18	testTimeout: 100019})2021runBaseTest("proxy (no freeze)", true, false)22runBaseTest("proxy (autofreeze)", true, true)23runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)2425function runBaseTest(name, autoFreeze, useListener) {26	const listener = useListener ? function() {} : undefined27	const {produce, produceWithPatches} = createPatchedImmer({28		autoFreeze29	})3031	// When `useListener` is true, append a function to the arguments of every32	// uncurried `produce` call in every test. This makes tests easier to read.33	function createPatchedImmer(options) {34		const immer = new Immer(options)3536		const {produce} = immer37		immer.produce = function(...args) {38			return typeof args[1] === "function" && args.length < 339				? produce(...args, listener)40				: produce(...args)41		}4243		return immer44	}4546	describe("map issues " + name, () => {47		test("#472 ", () => {48			const project = produce(new Map(), draft => {49				draft.set("bar1", {blocked: false})50				draft.set("bar2", {blocked: false})51			})5253			// Read before write -- no error54			produce(project, draft => {55				const bar1 = draft.get("bar1")56				const bar2 = draft.get("bar2")57				bar1.blocked = true58				bar2.blocked = true59			})6061			// Read/write interleaved -- error62			produce(project, draft => {63				const bar1 = draft.get("bar1")64				bar1.blocked = true65				const bar2 = draft.get("bar2")66				bar2.blocked = true // TypeError: "blocked" is read-only67			})68		})6970		test("#466 - setNoPatches", () => {71			const obj = {72				set: new Set()73			}7475			const result = produceWithPatches(obj, draft => {76				draft.set.add("abc")77			})78			expect(result).toEqual([79				{set: new Set(["abc"])},80				[{op: "add", path: ["set", 0], value: "abc"}],81				[{op: "remove", path: ["set", 0], value: "abc"}]82			])83		})8485		test("#466 - mapChangeBug ", () => {86			const obj = {87				map: new Map([88					[89						"a",90						new Map([91							["b", true],92							["c", true],93							["d", true]94						])95					],96					["b", new Map([["a", true]])],97					["c", new Map([["a", true]])],98					["d", new Map([["a", true]])]99				])100			}101			const result = produceWithPatches(obj, draft => {102				const aMap = draft.map.get("a")103				aMap.forEach((_, other) => {104					const otherMap = draft.map.get(other)105					otherMap.delete("a")106				})107			})108			expect(result).toEqual([109				{110					map: new Map([111						[112							"a",113							new Map([114								["b", true],115								["c", true],116								["d", true]117							])118						],119						["b", new Map()],120						["c", new Map()],121						["d", new Map()]122					])123				},124				[125					{126						op: "remove",127						path: ["map", "d", "a"]128					},129					{130						op: "remove",131						path: ["map", "c", "a"]132					},133					{134						op: "remove",135						path: ["map", "b", "a"]136					}137				],138				[139					{140						op: "add",141						path: ["map", "d", "a"],142						value: true143					},144					{145						op: "add",146						path: ["map", "c", "a"],147						value: true148					},149					{150						op: "add",151						path: ["map", "b", "a"],152						value: true153					}154				]155			])156		})157158		test("#466 - mapChangeBug2 ", () => {159			const obj = {160				map: new Map([161					[162						"a",163						new Map([164							["b", true],165							["c", true],166							["d", true]167						])168					],169					["b", new Map([["a", true]])],170					["c", new Map([["a", true]])],171					["d", new Map([["a", true]])]172				])173			}174			const obj1 = produce(obj, draft => {})175			const [result, p, ip] = produceWithPatches(obj1, draft => {176				const aMap = draft.map.get("a")177				aMap.forEach((_, other) => {178					const otherMap = draft.map.get(other)179					otherMap.delete("a")180				})181			})182			expect(result).toEqual({183				map: new Map([184					[185						"a",186						new Map([187							["b", true],188							["c", true],189							["d", true]190						])191					],192					["b", new Map([])],193					["c", new Map([])],194					["d", new Map([])]195				])196			})197			expect(p).toEqual([198				{199					op: "remove",200					path: ["map", "d", "a"]201				},202				{203					op: "remove",204					path: ["map", "c", "a"]205				},206				{207					op: "remove",208					path: ["map", "b", "a"]209				}210			])211			expect(ip).toEqual([212				{213					op: "add",214					path: ["map", "d", "a"],215					value: true216				},217218				{219					op: "add",220					path: ["map", "c", "a"],221					value: true222				},223				{224					op: "add",225					path: ["map", "b", "a"],226					value: true227				}228			])229		})230231		test("#586", () => {232			const base = new Set([1, 2])233			const set = produce(base, draftSet => {234				debugger235				expect(Array.from(draftSet)).toEqual([1, 2])236				draftSet.add(3)237			})238			expect(Array.from(set).sort()).toEqual([1, 2, 3])239		})240241		test("#627 - new map key with value=undefined", () => {242			const map = new Map()243			const map1 = produce(map, draft => {244				draft.set("key", undefined)245			})246			expect(map1.has("key")).toBe(true)247			expect(map1.get("key")).toBe(undefined)248		})249250		test("#663 - clear map", () => {251			const map = new Map([252				["a", "b"],253				["b", "c"]254			])255			const result = produceWithPatches(map, draft => {256				draft.clear()257			})258259			expect(result).toEqual([260				new Map(),261				[262					{op: "remove", path: ["a"]},263					{op: "remove", path: ["b"]}264				],265				[266					{op: "add", path: ["a"], value: "b"},267					{op: "add", path: ["b"], value: "c"}268				]269			])270		})271272		test("#680 - Clearing empty Set&Map should be noop", () => {273			const map = new Map()274			let result = produce(map, draft => {275				draft.clear()276			})277			expect(result).toBe(map)278279			const set = new Set()280			result = produce(set, draft => {281				draft.clear()282			})283			expect(result).toBe(set)284		})285286		test("#692 - idempotent plugin loading", () => {287			let mapType1288			produce(new Map(), draft => {289				mapType1 = draft.constructor290			})291292			enableMapSet()293			let mapType2294			produce(new Map(), draft => {295				mapType2 = draft.constructor296			})297			expect(mapType1).toBe(mapType2)298		})299300		test("#819 - Set with object maintains order when adding object", () => {301			const items = [302				{303					id: "a"304				},305				{306					id: "b"307				}308			]309310			const set = new Set([items[0]])311			const newSet = produce(set, draft => {312				draft.add(items[1])313			})314315			expect(Array.from(newSet)).toEqual([items[0], items[1]])316		})317318		// More specific varaint of above test covering case of adding non-object item319		test("#819 - Set with object maintains order when adding string", () => {320			const items = [321				{322					id: "a"323				},324				"b"325			]326327			const set = new Set([items[0]])328			const newSet = produce(set, draft => {329				draft.add(items[1])330			})331332			expect(Array.from(newSet)).toEqual([items[0], items[1]])333		})334	})335	describe("set issues " + name, () => {336		test("#819.A - maintains order when adding", () => {337			const objs = [338				"a",339				{340					id: "b"341				}342			]343344			const set = new Set([objs[0]])345			const newSet = produce(set, draft => {346				draft.add(objs[1])347			})348349			// passes350			expect(Array.from(newSet)).toEqual([objs[0], objs[1]])351		})352353		test("#819.B - maintains order when adding", () => {354			const objs = [355				{356					id: "a"357				},358				"b"359			]360361			const set = new Set([objs[0]])362			const newSet = produce(set, draft => {363				draft.add(objs[1])364			})365366			expect(Array.from(newSet)).toEqual([objs[0], objs[1]])367		})368	})369}370371// Bug reproduction: DraftSet leakage when placed in new object and set into Map372// This bug occurs when a plain object containing a draft Set is set into a DraftMap373describe("RTK-5159: DraftSet leakage in Map", () => {374	const {produce} = new Immer({autoFreeze: true})375376	test("DraftSet should not leak when placed in new object and set into Map", () => {377		const baseState = {378			map: new Map([["key1", {users: new Set()}]])379		}380381		// First produce: add a user382		const state1 = produce(baseState, draft => {383			const entry = draft.map.get("key1")384			entry.users.add({name: "user1"})385		})386387		// Second produce: create new object with existing Set and set into Map388		const state2 = produce(state1, draft => {389			const existingUsers = draft.map.get("key1")?.users ?? new Set()390			const newEntry = {users: existingUsers} // New plain object with existing draft Set391			draft.map.set("key1", newEntry)392			newEntry.users.add({name: "user2"})393		})394395		// Should not throw "Cannot use a proxy that has been revoked"396		const users = state2.map.get("key1").users397398		expect(users).toBeInstanceOf(Set)399		expect([...users].map(u => u.name)).toEqual(["user1", "user2"])400	})401402	test("DraftSet in new object set into Map should finalize correctly", () => {403		const baseState = {404			map: new Map([["key1", {items: new Set([1, 2, 3])}]])405		}406407		const result = produce(baseState, draft => {408			const existingItems = draft.map.get("key1").items409			// Create a new plain object containing the draft Set410			const newEntry = {items: existingItems, extra: "data"}411			draft.map.set("key1", newEntry)412			newEntry.items.add(4)413		})414415		// Verify the result is properly finalized (not a draft/proxy)416		const items = result.map.get("key1").items417		expect(items).toBeInstanceOf(Set)418		expect([...items]).toEqual([1, 2, 3, 4])419		expect(result.map.get("key1").extra).toBe("data")420	})421422	// Test for DraftSet.add() with non-draft object containing nested draft423	// This covers the handleCrossReference() call in DraftSet.add()424	test("DraftSet.add() should handle non-draft object containing nested draft", () => {425		const baseState = {426			items: [{id: 1, name: "item1"}],427			itemSet: new Set()428		}429430		const result = produce(baseState, draft => {431			// Get a draft of an existing item432			const draftItem = draft.items[0]433			// Create a new plain object that contains the draft434			const wrapper = {item: draftItem, extra: "wrapper data"}435			// Add the non-draft wrapper (containing a draft) to the Set436			draft.itemSet.add(wrapper)437			// Modify the draft item after adding438			draftItem.name = "modified"439		})440441		// The wrapper should be finalized correctly442		const addedItems = [...result.itemSet]443		expect(addedItems).toHaveLength(1)444		expect(addedItems[0].item.id).toBe(1)445		expect(addedItems[0].item.name).toBe("modified")446		expect(addedItems[0].extra).toBe("wrapper data")447		// Verify it's not a proxy448		expect(() => JSON.stringify(result)).not.toThrow()449	})450451	test("DraftSet.add() should handle deeply nested drafts in plain objects", () => {452		const baseState = {453			nested: {454				deep: {455					value: "original"456				}457			},458			mySet: new Set()459		}460461		const result = produce(baseState, draft => {462			// Get a draft of a deeply nested object463			const deepDraft = draft.nested.deep464			// Create a plain object hierarchy containing the draft465			const wrapper = {466				level1: {467					level2: {468						draftRef: deepDraft469					}470				}471			}472			// Add to Set473			draft.mySet.add(wrapper)474			// Modify the draft475			deepDraft.value = "modified"476		})477478		const items = [...result.mySet]479		expect(items).toHaveLength(1)480		expect(items[0].level1.level2.draftRef.value).toBe("modified")481		// Should not throw when accessing482		expect(() => JSON.stringify(result)).not.toThrow()483	})484})