map-set.js
This file
Path
__tests__/map-set.js
514 lines · 11.7 KiB · JavaScript
Last changed by
fix: improve DraftMap.{entries,values}() compatibility#1228 (#1228)Marcel Jackwerthbefore adoption858d036
History of this fileTake it
The walk stopped after 200 commits: lines older than feba5d1 point at it.
chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
line 1why, one step back1"use strict"chore: Migrate test setup to Vitest (#1162)Mark Eriksonbefore adoption4b8bcc5
line 2why, one step back2import {vi} from "vitest"chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 3–8why, one step back3import {4 Immer,5 nothing,6 original,7 isDraft,8 immerable,Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 9why, one step back9 enablePatches,chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 10–11why, one step back10 enableMapSet11} from "../src/immer"Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 12why, one step back12import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/utils/common"chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
line 13why, one step back13Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 14–15why, one step back14enableMapSet()15enablePatches()chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
line 16why, one step back16chore: Migrate test setup to Vitest (#1162)Mark Eriksonbefore adoption4b8bcc5
lines 17–19why, one step back17vi.setConfig({18 testTimeout: 100019})chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 20–21why, one step back2021runBaseTest("proxy (no freeze)", true, false)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 22–23why, one step back22runBaseTest("proxy (autofreeze)", true, true)23runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
line 24why, one step back24Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 25why, one step back25function runBaseTest(name, autoFreeze, useListener) {chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f
line 26why, one step back26 const listener = useListener ? function () {} : undefinedchore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 27–36why, one step back27 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} = immerchore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f
line 37why, one step back37 immer.produce = function (...args) {chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 38–126why, one step back38 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",perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 127why, one step back127 path: ["map", "d", "a"]chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 128–134why, one step back128 },129 {130 op: "remove",131 path: ["map", "c", "a"]132 },133 {134 op: "remove",perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 135why, one step back135 path: ["map", "b", "a"]chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 136–140why, one step back136 }137 ],138 [139 {140 op: "add",perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 141why, one step back141 path: ["map", "d", "a"],chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 142–150why, one step back142 value: true143 },144 {145 op: "add",146 path: ["map", "c", "a"],147 value: true148 },149 {150 op: "add",perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 151why, one step back151 path: ["map", "b", "a"],chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 152–199why, one step back152 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",perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 200why, one step back200 path: ["map", "d", "a"]chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 201–207why, one step back201 },202 {203 op: "remove",204 path: ["map", "c", "a"]205 },206 {207 op: "remove",perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 208why, one step back208 path: ["map", "b", "a"]chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 209–213why, one step back209 }210 ])211 expect(ip).toEqual([212 {213 op: "add",perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 214why, one step back214 path: ["map", "d", "a"],chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 215–216why, one step back215 value: true216 },perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 217why, one step back217chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 218–224why, one step back218 {219 op: "add",220 path: ["map", "c", "a"],221 value: true222 },223 {224 op: "add",perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202
line 225why, one step back225 path: ["map", "b", "a"],chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
lines 226–298why, one step back226 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 })chore: Add failing test Set ordering #819 (#820)Chris Santamariabefore adoption847b662
lines 299–333why, one step back299300 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 })fix: improve DraftMap.{entries,values}() compatibility#1228 (#1228)Marcel Jackwerthbefore adoption858d036
lines 334–363why, one step back334335 it("IterableIterator should return itself", () => {336 const baseState = {337 map: new Map([1, 2, 3].map(i => [i, `Item ${i}`]))338 }339340 produce(baseState, draft => {341 const it = draft.map.values()342 expect(it.next()).toEqual({value: "Item 1", done: false})343344 const itOfIt = it[Symbol.iterator]()345 expect(itOfIt.next()).toEqual({value: "Item 2", done: false})346 expect(itOfIt).toBe(it)347348 const it2 = draft.map.values()349 expect(it2.next()).toEqual({value: "Item 1", done: false})350 })351 })352353 it("is compatible with ES2025 features", () => {354 const baseState = {355 map: new Map([1, 2, 3].map(i => [i, `Item ${i}`]))356 }357358 const result = produce(baseState, draft => {359 draft.map = new Map(draft.map.entries().filter(([k]) => k % 2 === 1))360 })361362 expect(result.map.keys().toArray()).toEqual([1, 3])363 })chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
line 364why, one step back364 })fix: Preserve insertion order of Sets, fixes #819 (#976)jdipbefore adoptionb3eeb69
lines 365–398why, one step back365 describe("set issues " + name, () => {366 test("#819.A - maintains order when adding", () => {367 const objs = [368 "a",369 {370 id: "b"371 }372 ]373374 const set = new Set([objs[0]])375 const newSet = produce(set, draft => {376 draft.add(objs[1])377 })378379 // passes380 expect(Array.from(newSet)).toEqual([objs[0], objs[1]])381 })382383 test("#819.B - maintains order when adding", () => {384 const objs = [385 {386 id: "a"387 },388 "b"389 ]390391 const set = new Set([objs[0]])392 const newSet = produce(set, draft => {393 draft.add(objs[1])394 })395396 expect(Array.from(newSet)).toEqual([objs[0], objs[1]])397 })398 })chore: remove debugger statementMichel Weststratebefore adoptionfeba5d1
line 399why, one step back399}fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58
lines 400–514why, one step back400401// Bug reproduction: DraftSet leakage when placed in new object and set into Map402// This bug occurs when a plain object containing a draft Set is set into a DraftMap403describe("RTK-5159: DraftSet leakage in Map", () => {404 const {produce} = new Immer({autoFreeze: true})405406 test("DraftSet should not leak when placed in new object and set into Map", () => {407 const baseState = {408 map: new Map([["key1", {users: new Set()}]])409 }410411 // First produce: add a user412 const state1 = produce(baseState, draft => {413 const entry = draft.map.get("key1")414 entry.users.add({name: "user1"})415 })416417 // Second produce: create new object with existing Set and set into Map418 const state2 = produce(state1, draft => {419 const existingUsers = draft.map.get("key1")?.users ?? new Set()420 const newEntry = {users: existingUsers} // New plain object with existing draft Set421 draft.map.set("key1", newEntry)422 newEntry.users.add({name: "user2"})423 })424425 // Should not throw "Cannot use a proxy that has been revoked"426 const users = state2.map.get("key1").users427428 expect(users).toBeInstanceOf(Set)429 expect([...users].map(u => u.name)).toEqual(["user1", "user2"])430 })431432 test("DraftSet in new object set into Map should finalize correctly", () => {433 const baseState = {434 map: new Map([["key1", {items: new Set([1, 2, 3])}]])435 }436437 const result = produce(baseState, draft => {438 const existingItems = draft.map.get("key1").items439 // Create a new plain object containing the draft Set440 const newEntry = {items: existingItems, extra: "data"}441 draft.map.set("key1", newEntry)442 newEntry.items.add(4)443 })444445 // Verify the result is properly finalized (not a draft/proxy)446 const items = result.map.get("key1").items447 expect(items).toBeInstanceOf(Set)448 expect([...items]).toEqual([1, 2, 3, 4])449 expect(result.map.get("key1").extra).toBe("data")450 })451452 // Test for DraftSet.add() with non-draft object containing nested draft453 // This covers the handleCrossReference() call in DraftSet.add()454 test("DraftSet.add() should handle non-draft object containing nested draft", () => {455 const baseState = {456 items: [{id: 1, name: "item1"}],457 itemSet: new Set()458 }459460 const result = produce(baseState, draft => {461 // Get a draft of an existing item462 const draftItem = draft.items[0]463 // Create a new plain object that contains the draft464 const wrapper = {item: draftItem, extra: "wrapper data"}465 // Add the non-draft wrapper (containing a draft) to the Set466 draft.itemSet.add(wrapper)467 // Modify the draft item after adding468 draftItem.name = "modified"469 })470471 // The wrapper should be finalized correctly472 const addedItems = [...result.itemSet]473 expect(addedItems).toHaveLength(1)474 expect(addedItems[0].item.id).toBe(1)475 expect(addedItems[0].item.name).toBe("modified")476 expect(addedItems[0].extra).toBe("wrapper data")477 // Verify it's not a proxy478 expect(() => JSON.stringify(result)).not.toThrow()479 })480481 test("DraftSet.add() should handle deeply nested drafts in plain objects", () => {482 const baseState = {483 nested: {484 deep: {485 value: "original"486 }487 },488 mySet: new Set()489 }490491 const result = produce(baseState, draft => {492 // Get a draft of a deeply nested object493 const deepDraft = draft.nested.deep494 // Create a plain object hierarchy containing the draft495 const wrapper = {496 level1: {497 level2: {498 draftRef: deepDraft499 }500 }501 }502 // Add to Set503 draft.mySet.add(wrapper)504 // Modify the draft505 deepDraft.value = "modified"506 })507508 const items = [...result.mySet]509 expect(items).toHaveLength(1)510 expect(items[0].level1.level2.draftRef.value).toBe("modified")511 // Should not throw when accessing512 expect(() => JSON.stringify(result)).not.toThrow()513 })514})