Skip to content
Myr

patch.js

This file

Path

__tests__/patch.js

1,076 lines · 18.3 KiB · JavaScript

Last changed by

Added regression test to verify #588Michel Weststratebefore adoption198e05f

History of this file

Take it

1"use strict"2import produce, {3	setUseProxies,4	applyPatches,5	produceWithPatches,6	enableAllPlugins,7	isDraft,8	immerable9} from "../src/immer"1011enableAllPlugins()1213jest.setTimeout(1000)1415function runPatchTest(base, producer, patches, inversePathes) {16	let resultProxies, resultEs51718	function runPatchTestHelper() {19		let recordedPatches20		let recordedInversePatches21		const res = produce(base, producer, (p, i) => {22			recordedPatches = p23			recordedInversePatches = i24		})2526		test("produces the correct patches", () => {27			expect(recordedPatches).toEqual(patches)28			if (inversePathes) expect(recordedInversePatches).toEqual(inversePathes)29		})3031		test("patches are replayable", () => {32			expect(applyPatches(base, recordedPatches)).toEqual(res)33		})3435		test("patches can be reversed", () => {36			expect(applyPatches(res, recordedInversePatches)).toEqual(base)37		})3839		return res40	}4142	describe(`proxy`, () => {43		setUseProxies(true)44		resultProxies = runPatchTestHelper()45	})4647	describe(`es5`, () => {48		setUseProxies(false)49		resultEs5 = runPatchTestHelper()50		test("ES5 and Proxy implementation yield same result", () => {51			expect(resultEs5).toEqual(resultProxies)52		})53	})5455	return resultProxies56}5758describe("applyPatches", () => {59	it("mutates the base state when it is a draft", () => {60		produce({a: 1}, draft => {61			const result = applyPatches(draft, [62				{op: "replace", path: ["a"], value: 2}63			])64			expect(result).toBe(draft)65			expect(draft.a).toBe(2)66		})67	})68	it("produces a copy of the base state when not a draft", () => {69		const base = {a: 1}70		const result = applyPatches(base, [{op: "replace", path: ["a"], value: 2}])71		expect(result).not.toBe(base)72		expect(result.a).toBe(2)73		expect(base.a).toBe(1)74	})75	it('throws when `op` is not "add", "replace", nor "remove"', () => {76		expect(() => {77			const patch = {op: "copy", from: [0], path: [1]}78			applyPatches([2], [patch])79		}).toThrowErrorMatchingSnapshot()80	})81	it("throws when `path` cannot be resolved", () => {82		// missing parent83		expect(() => {84			const patch = {op: "add", path: ["a", "b"], value: 1}85			applyPatches({}, [patch])86		}).toThrowErrorMatchingSnapshot()8788		// missing grand-parent89		expect(() => {90			const patch = {op: "add", path: ["a", "b", "c"], value: 1}91			applyPatches({}, [patch])92		}).toThrowErrorMatchingSnapshot()93	})94	it("applied patches cannot be modified", () => {95		// see also: https://github.com/immerjs/immer/issues/41196		const s0 = {97			items: [1]98		}99100		const [s1, p1] = produceWithPatches(s0, draft => {101			draft.items = []102		})103104		const replaceValueBefore = p1[0].value.slice()105106		const [s2, p2] = produceWithPatches(s1, draft => {107			draft.items.push(2)108		})109110		applyPatches(s0, [...p1, ...p2])111112		const replaceValueAfter = p1[0].value.slice()113114		expect(replaceValueAfter).toStrictEqual(replaceValueBefore)115	})116})117118describe("simple assignment - 1", () => {119	runPatchTest(120		{x: 3},121		d => {122			d.x++123		},124		[{op: "replace", path: ["x"], value: 4}]125	)126})127128describe("simple assignment - 2", () => {129	runPatchTest(130		{x: {y: 4}},131		d => {132			d.x.y++133		},134		[{op: "replace", path: ["x", "y"], value: 5}]135	)136})137138describe("simple assignment - 3", () => {139	runPatchTest(140		{x: [{y: 4}]},141		d => {142			d.x[0].y++143		},144		[{op: "replace", path: ["x", 0, "y"], value: 5}]145	)146})147148describe("simple assignment - 4", () => {149	runPatchTest(150		new Map([["x", {y: 4}]]),151		d => {152			d.get("x").y++153		},154		[{op: "replace", path: ["x", "y"], value: 5}],155		[{op: "replace", path: ["x", "y"], value: 4}]156	)157})158159describe("simple assignment - 5", () => {160	runPatchTest(161		{x: new Map([["y", 4]])},162		d => {163			d.x.set("y", 5)164		},165		[{op: "replace", path: ["x", "y"], value: 5}],166		[{op: "replace", path: ["x", "y"], value: 4}]167	)168})169170describe("simple assignment - 6", () => {171	runPatchTest(172		new Map([["x", 1]]),173		d => {174			// Map.prototype.set should return the Map itself175			const res = d.set("x", 2)176			res.set("y", 3)177		},178		[179			{op: "replace", path: ["x"], value: 2},180			{op: "add", path: ["y"], value: 3}181		],182		[183			{op: "replace", path: ["x"], value: 1},184			{op: "remove", path: ["y"]}185		]186	)187})188189describe("simple assignment - 7", () => {190	const key1 = {prop: "val1"}191	const key2 = {prop: "val2"}192	runPatchTest(193		{x: new Map([[key1, 4]])},194		d => {195			d.x.set(key1, 5)196			d.x.set(key2, 6)197		},198		[199			{op: "replace", path: ["x", key1], value: 5},200			{op: "add", path: ["x", key2], value: 6}201		],202		[203			{op: "replace", path: ["x", key1], value: 4},204			{op: "remove", path: ["x", key2]}205		]206	)207})208209describe("delete 1", () => {210	runPatchTest(211		{x: {y: 4}},212		d => {213			delete d.x214		},215		[{op: "remove", path: ["x"]}]216	)217})218219describe("delete 2", () => {220	runPatchTest(221		new Map([["x", 1]]),222		d => {223			d.delete("x")224		},225		[{op: "remove", path: ["x"]}],226		[{op: "add", path: ["x"], value: 1}]227	)228})229230describe("delete 3", () => {231	runPatchTest(232		{x: new Map([["y", 1]])},233		d => {234			d.x.delete("y")235		},236		[{op: "remove", path: ["x", "y"]}],237		[{op: "add", path: ["x", "y"], value: 1}]238	)239})240241describe("delete 5", () => {242	const key1 = {prop: "val1"}243	const key2 = {prop: "val2"}244	runPatchTest(245		{246			x: new Map([247				[key1, 1],248				[key2, 2]249			])250		},251		d => {252			d.x.delete(key1)253			d.x.delete(key2)254		},255		[256			{op: "remove", path: ["x", key1]},257			{op: "remove", path: ["x", key2]}258		],259		[260			{op: "add", path: ["x", key1], value: 1},261			{op: "add", path: ["x", key2], value: 2}262		]263	)264})265266describe("delete 6", () => {267	runPatchTest(268		new Set(["x", 1]),269		d => {270			d.delete("x")271		},272		[{op: "remove", path: [0], value: "x"}],273		[{op: "add", path: [0], value: "x"}]274	)275})276277describe("delete 7", () => {278	runPatchTest(279		{x: new Set(["y", 1])},280		d => {281			d.x.delete("y")282		},283		[{op: "remove", path: ["x", 0], value: "y"}],284		[{op: "add", path: ["x", 0], value: "y"}]285	)286})287288describe("renaming properties", () => {289	describe("nested object (no changes)", () => {290		runPatchTest(291			{a: {b: 1}},292			d => {293				d.x = d.a294				delete d.a295			},296			[297				{op: "add", path: ["x"], value: {b: 1}},298				{op: "remove", path: ["a"]}299			]300		)301	})302303	describe("nested map (no changes)", () => {304		runPatchTest(305			new Map([["a", new Map([["b", 1]])]]),306			d => {307				d.set("x", d.get("a"))308				d.delete("a")309			},310			[311				{op: "add", path: ["x"], value: new Map([["b", 1]])},312				{op: "remove", path: ["a"]}313			],314			[315				{op: "remove", path: ["x"]},316				{op: "add", path: ["a"], value: new Map([["b", 1]])}317			]318		)319	})320321	describe("nested object (with changes)", () => {322		runPatchTest(323			{a: {b: 1, c: 1}},324			d => {325				let a = d.a326				a.b = 2 // change327				delete a.c // delete328				a.y = 2 // add329330				// rename331				d.x = a332				delete d.a333			},334			[335				{op: "add", path: ["x"], value: {b: 2, y: 2}},336				{op: "remove", path: ["a"]}337			]338		)339	})340341	describe("nested map (with changes)", () => {342		runPatchTest(343			new Map([344				[345					"a",346					new Map([347						["b", 1],348						["c", 1]349					])350				]351			]),352			d => {353				let a = d.get("a")354				a.set("b", 2) // change355				a.delete("c") // delete356				a.set("y", 2) // add357358				// rename359				d.set("x", a)360				d.delete("a")361			},362			[363				{364					op: "add",365					path: ["x"],366					value: new Map([367						["b", 2],368						["y", 2]369					])370				},371				{op: "remove", path: ["a"]}372			],373			[374				{op: "remove", path: ["x"]},375				{376					op: "add",377					path: ["a"],378					value: new Map([379						["b", 1],380						["c", 1]381					])382				}383			]384		)385	})386387	describe("deeply nested object (with changes)", () => {388		runPatchTest(389			{a: {b: {c: 1, d: 1}}},390			d => {391				let b = d.a.b392				b.c = 2 // change393				delete b.d // delete394				b.y = 2 // add395396				// rename397				d.a.x = b398				delete d.a.b399			},400			[401				{op: "add", path: ["a", "x"], value: {c: 2, y: 2}},402				{op: "remove", path: ["a", "b"]}403			]404		)405	})406407	describe("deeply nested map (with changes)", () => {408		runPatchTest(409			new Map([410				[411					"a",412					new Map([413						[414							"b",415							new Map([416								["c", 1],417								["d", 1]418							])419						]420					])421				]422			]),423			d => {424				let b = d.get("a").get("b")425				b.set("c", 2) // change426				b.delete("d") // delete427				b.set("y", 2) // add428429				// rename430				d.get("a").set("x", b)431				d.get("a").delete("b")432			},433			[434				{435					op: "add",436					path: ["a", "x"],437					value: new Map([438						["c", 2],439						["y", 2]440					])441				},442				{op: "remove", path: ["a", "b"]}443			],444			[445				{op: "remove", path: ["a", "x"]},446				{447					op: "add",448					path: ["a", "b"],449					value: new Map([450						["c", 1],451						["d", 1]452					])453				}454			]455		)456	})457})458459describe("minimum amount of changes", () => {460	runPatchTest(461		{x: 3, y: {a: 4}, z: 3},462		d => {463			d.y.a = 4464			d.y.b = 5465			Object.assign(d, {x: 4, y: {a: 2}})466		},467		[468			{op: "replace", path: ["x"], value: 4},469			{op: "replace", path: ["y"], value: {a: 2}}470		]471	)472})473474describe("arrays - prepend", () => {475	runPatchTest(476		{x: [1, 2, 3]},477		d => {478			d.x.unshift(4)479		},480		[{op: "add", path: ["x", 0], value: 4}]481	)482})483484describe("arrays - multiple prepend", () => {485	runPatchTest(486		{x: [1, 2, 3]},487		d => {488			d.x.unshift(4)489			d.x.unshift(5)490		},491		[492			{op: "add", path: ["x", 0], value: 5},493			{op: "add", path: ["x", 1], value: 4}494		]495	)496})497498describe("arrays - splice middle", () => {499	runPatchTest(500		{x: [1, 2, 3]},501		d => {502			d.x.splice(1, 1)503		},504		[{op: "remove", path: ["x", 1]}]505	)506})507508describe("arrays - multiple splice", () => {509	runPatchTest(510		[0, 1, 2, 3, 4, 5, 0],511		d => {512			d.splice(4, 2, 3)513			d.splice(1, 2, 3)514		},515		[516			{op: "replace", path: [1], value: 3},517			{op: "replace", path: [2], value: 3},518			{op: "remove", path: [5]},519			{op: "remove", path: [4]}520		]521	)522})523524describe("arrays - modify and shrink", () => {525	runPatchTest(526		{x: [1, 2, 3]},527		d => {528			d.x[0] = 4529			d.x.length = 2530		},531		[532			{op: "replace", path: ["x", 0], value: 4},533			{op: "remove", path: ["x", 2]}534		],535		[536			{op: "replace", path: ["x", 0], value: 1},537			{op: "add", path: ["x", 2], value: 3}538		]539	)540})541542describe("arrays - prepend then splice middle", () => {543	runPatchTest(544		{x: [1, 2, 3]},545		d => {546			d.x.unshift(4)547			d.x.splice(2, 1)548		},549		[550			{op: "replace", path: ["x", 0], value: 4},551			{op: "replace", path: ["x", 1], value: 1}552		]553	)554})555556describe("arrays - splice middle then prepend", () => {557	runPatchTest(558		{x: [1, 2, 3]},559		d => {560			d.x.splice(1, 1)561			d.x.unshift(4)562		},563		[564			{op: "replace", path: ["x", 0], value: 4},565			{op: "replace", path: ["x", 1], value: 1}566		]567	)568})569570describe("arrays - truncate", () => {571	runPatchTest(572		{x: [1, 2, 3]},573		d => {574			d.x.length -= 2575		},576		[577			{op: "remove", path: ["x", 2]},578			{op: "remove", path: ["x", 1]}579		],580		[581			{op: "add", path: ["x", 1], value: 2},582			{op: "add", path: ["x", 2], value: 3}583		]584	)585})586587describe("arrays - pop twice", () => {588	runPatchTest(589		{x: [1, 2, 3]},590		d => {591			d.x.pop()592			d.x.pop()593		},594		[595			{op: "remove", path: ["x", 2]},596			{op: "remove", path: ["x", 1]}597		]598	)599})600601describe("arrays - push multiple", () => {602	runPatchTest(603		{x: [1, 2, 3]},604		d => {605			d.x.push(4, 5)606		},607		[608			{op: "add", path: ["x", 3], value: 4},609			{op: "add", path: ["x", 4], value: 5}610		],611		[612			{op: "remove", path: ["x", 4]},613			{op: "remove", path: ["x", 3]}614		]615	)616})617618describe("arrays - splice (expand)", () => {619	runPatchTest(620		{x: [1, 2, 3]},621		d => {622			d.x.splice(1, 1, 4, 5, 6)623		},624		[625			{op: "replace", path: ["x", 1], value: 4},626			{op: "add", path: ["x", 2], value: 5},627			{op: "add", path: ["x", 3], value: 6}628		],629		[630			{op: "replace", path: ["x", 1], value: 2},631			{op: "remove", path: ["x", 3]},632			{op: "remove", path: ["x", 2]}633		]634	)635})636637describe("arrays - splice (shrink)", () => {638	runPatchTest(639		{x: [1, 2, 3, 4, 5]},640		d => {641			d.x.splice(1, 3, 6)642		},643		[644			{op: "replace", path: ["x", 1], value: 6},645			{op: "remove", path: ["x", 3]},646			{op: "remove", path: ["x", 2]}647		],648		[649			{op: "replace", path: ["x", 1], value: 2},650			{op: "add", path: ["x", 2], value: 3},651			{op: "add", path: ["x", 3], value: 4}652		]653	)654})655656describe("arrays - delete", () => {657	runPatchTest(658		{659			x: [660				{a: 1, b: 2},661				{c: 3, d: 4}662			]663		},664		d => {665			delete d.x[1].c666		},667		[{op: "remove", path: ["x", 1, "c"]}]668	)669})670671describe("sets - add - 1", () => {672	runPatchTest(673		new Set([1]),674		d => {675			d.add(2)676		},677		[{op: "add", path: [1], value: 2}],678		[{op: "remove", path: [1], value: 2}]679	)680})681682describe("sets - add, delete, add - 1", () => {683	runPatchTest(684		new Set([1]),685		d => {686			d.add(2)687			d.delete(2)688			d.add(2)689		},690		[{op: "add", path: [1], value: 2}],691		[{op: "remove", path: [1], value: 2}]692	)693})694695describe("sets - add, delete, add - 2", () => {696	runPatchTest(697		new Set([2, 1]),698		d => {699			d.add(2)700			d.delete(2)701			d.add(2)702		},703		[],704		[]705	)706})707708describe("sets - mutate - 1", () => {709	const findById = (set, id) => {710		for (const item of set) {711			if (item.id === id) return item712		}713	}714	runPatchTest(715		new Set([716			{id: 1, val: "We"},717			{id: 2, val: "will"}718		]),719		d => {720			const obj1 = findById(d, 1)721			const obj2 = findById(d, 2)722			obj1.val = "rock"723			obj2.val = "you"724		},725		[726			{op: "remove", path: [0], value: {id: 1, val: "We"}},727			{op: "remove", path: [1], value: {id: 2, val: "will"}},728			{op: "add", path: [0], value: {id: 1, val: "rock"}},729			{op: "add", path: [1], value: {id: 2, val: "you"}}730		],731		[732			{op: "remove", path: [1], value: {id: 2, val: "you"}},733			{op: "remove", path: [0], value: {id: 1, val: "rock"}},734			{op: "add", path: [1], value: {id: 2, val: "will"}},735			{op: "add", path: [0], value: {id: 1, val: "We"}}736		]737	)738})739740describe("arrays - splice should should result in remove op.", () => {741	runPatchTest(742		[1, 2],743		d => {744			d.splice(1, 1)745		},746		[{op: "remove", path: [1]}],747		[{op: "add", path: [1], value: 2}]748	)749})750751describe("arrays - NESTED splice should should result in remove op.", () => {752	runPatchTest(753		{a: {b: {c: [1, 2]}}},754		d => {755			d.a.b.c.splice(1, 1)756		},757		[{op: "remove", path: ["a", "b", "c", 1]}],758		[{op: "add", path: ["a", "b", "c", 1], value: 2}]759	)760})761762describe("simple replacement", () => {763	runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])764})765766describe("same value replacement - 1", () => {767	runPatchTest(768		{x: {y: 3}},769		d => {770			const a = d.x771			d.x = a772		},773		[]774	)775})776777describe("same value replacement - 2", () => {778	runPatchTest(779		{x: {y: 3}},780		d => {781			const a = d.x782			d.x = 4783			d.x = a784		},785		[]786	)787})788789describe("same value replacement - 3", () => {790	runPatchTest(791		{x: 3},792		d => {793			d.x = 3794		},795		[]796	)797})798799describe("same value replacement - 4", () => {800	runPatchTest(801		{x: 3},802		d => {803			d.x = 4804			d.x = 3805		},806		[]807	)808})809810describe("same value replacement - 5", () => {811	runPatchTest(812		new Map([["x", 3]]),813		d => {814			d.set("x", 4)815			d.set("x", 3)816		},817		[],818		[]819	)820})821822describe("same value replacement - 6", () => {823	runPatchTest(824		new Set(["x", 3]),825		d => {826			d.delete("x")827			d.add("x")828		},829		[],830		[]831	)832})833834describe("simple delete", () => {835	runPatchTest(836		{x: 2},837		d => {838			delete d.x839		},840		[841			{842				op: "remove",843				path: ["x"]844			}845		]846	)847})848849describe("patch compressions yields correct results", () => {850	let p1, p2851	runPatchTest(852		{},853		d => {854			d.x = {test: true}855		},856		(p1 = [857			{858				op: "add",859				path: ["x"],860				value: {861					test: true862				}863			}864		])865	)866	runPatchTest(867		{x: {test: true}},868		d => {869			delete d.x870		},871		(p2 = [872			{873				op: "remove",874				path: ["x"]875			}876		])877	)878	const res = runPatchTest(879		{},880		d => {881			applyPatches(d, [...p1, ...p2])882		},883		[]884	)885886	expect(res).toEqual({})887})888889describe("change then delete property", () => {890	const res = runPatchTest(891		{892			x: 1893		},894		d => {895			d.x = 2896			delete d.x897		},898		[899			{900				op: "remove",901				path: ["x"]902			}903		]904	)905	test("valid result", () => {906		expect(res).toEqual({})907	})908})909910test("replaying patches with interweaved replacements should work correctly", () => {911	const patches = []912	const s0 = {x: 1}913914	const s1 = produce(915		s0,916		draft => {917			draft.x = 2918		},919		p => {920			patches.push(...p)921		}922	)923924	const s2 = produce(925		s1,926		draft => {927			return {x: 0}928		},929		p => {930			patches.push(...p)931		}932	)933934	const s3 = produce(935		s2,936		draft => {937			draft.x--938		},939		p => {940			patches.push(...p)941		}942	)943944	expect(s3).toEqual({x: -1}) // correct result945	expect(applyPatches(s0, patches)).toEqual({x: -1}) // correct replay946947	// manual replay on a draft should also be correct948	expect(949		produce(s0, draft => {950			return applyPatches(draft, patches)951		})952	).toEqual({x: -1})953})954955test.skip("#468", () => {956	const item = {id: 1}957958	const state = [item]959960	const [nextState, patches] = produceWithPatches(state, draft => {961		draft[0].id = 2962		draft[1] = item963	})964965	expect(nextState).toMatchInlineSnapshot(`966		Array [967		  Object {968		    "id": 2,969		  },970		  Object {971		    "id": 1,972		  },973		]974	`)975	expect(patches).toMatchInlineSnapshot(`976				Array [977				  Object {978				    "op": "replace",979				    "path": Array [980				      0,981				      "id",982				    ],983				    "value": 2,984				  },985				  Object {986				    "op": "add",987				    "path": Array [988				      0,989				    ],990				    "value": Object {991				      "id": 2,992				    },993				  },994				]995		`)996997	const final = applyPatches(state, patches)998	expect(final).toEqual(nextState)999})10001001test("#521", () => {1002	const state = new Map()10031004	const [nextState, patches] = produceWithPatches(state, draft => {1005		draft.set("hello", new Set(["world"]))1006	})10071008	let patchedState = applyPatches(state, patches)1009	expect(patchedState).toEqual(nextState)10101011	const [nextStateV2, patchesV2] = produceWithPatches(nextState, draft => {1012		draft.get("hello").add("immer")1013	})10141015	expect(applyPatches(nextState, patchesV2)).toEqual(1016		new Map([["hello", new Set(["world", "immer"])]])1017	)1018})10191020test("#559 patches works in a nested reducer with proxies", () => {1021	setUseProxies(true)10221023	const state = {1024		x: 1,1025		sub: {1026			y: [{a: 0}, {a: 1}]1027		}1028	}10291030	const changes = []1031	const inverseChanges = []10321033	const newState = produce(state, draft => {1034		draft.sub = produce(1035			draft.sub,1036			draft => {1037				draft.y.pop()1038			},1039			(patches, inversePatches) => {1040				expect(isDraft(inversePatches[0].value)).toBeFalsy()1041				expect(inversePatches[0].value).toMatchObject({a: 1})1042				changes.push(...patches)1043				inverseChanges.push(...inversePatches)1044			}1045		)1046	})10471048	const reversedSubState = applyPatches(newState.sub, inverseChanges)10491050	expect(reversedSubState).toMatchObject(state.sub)1051})10521053describe("#588", () => {1054	const reference = {value: {num: 53}}10551056	class Base {1057		[immerable] = true1058		get nested() {1059			return reference.value1060		}1061		set nested(value) {}1062	}10631064	let base = new Base()10651066	runPatchTest(1067		base,1068		vdraft => {1069			reference.value = vdraft1070			produce(base, bdraft => {1071				bdraft.nested.num = 421072			})1073		},1074		[{op: "add", path: ["num"], value: 42}]1075	)1076})