map-set.js
This file
Path
__tests__/map-set.js
535 lines · 12.4 KiB · JavaScript
Last changed by
Merge pull request #1289 from maximilliangrand/fix/array-methods-noop-structural-sharingMark Eriksonbefore adoption907395a
History of this fileTake 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 })334335 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 })364 })365 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 })398399 test("reading (but not modifying) a nested object inside a Set does not leak the copy", () => {400 const untouched = {nested: {a: 1}}401 const base = new Set([untouched, {x: 1}])402 const next = produce(base, draft => {403 for (const v of draft) {404 if (v.nested) {405 // Read only - creates a child draft (and a stray copy_406 // on the parent) but modifies nothing407 expect(v.nested.a).toBe(1)408 } else {409 v.x = 2410 }411 }412 })413 expect(next).not.toBe(base)414 const finalUntouched = Array.from(next).find(v => v.nested)415 expect(finalUntouched).toBe(untouched)416 expect(finalUntouched.nested.a).toBe(1)417 expect(isDraft(finalUntouched.nested)).toBe(false)418 })419 })420}421422// Bug reproduction: DraftSet leakage when placed in new object and set into Map423// This bug occurs when a plain object containing a draft Set is set into a DraftMap424describe("RTK-5159: DraftSet leakage in Map", () => {425 const {produce} = new Immer({autoFreeze: true})426427 test("DraftSet should not leak when placed in new object and set into Map", () => {428 const baseState = {429 map: new Map([["key1", {users: new Set()}]])430 }431432 // First produce: add a user433 const state1 = produce(baseState, draft => {434 const entry = draft.map.get("key1")435 entry.users.add({name: "user1"})436 })437438 // Second produce: create new object with existing Set and set into Map439 const state2 = produce(state1, draft => {440 const existingUsers = draft.map.get("key1")?.users ?? new Set()441 const newEntry = {users: existingUsers} // New plain object with existing draft Set442 draft.map.set("key1", newEntry)443 newEntry.users.add({name: "user2"})444 })445446 // Should not throw "Cannot use a proxy that has been revoked"447 const users = state2.map.get("key1").users448449 expect(users).toBeInstanceOf(Set)450 expect([...users].map(u => u.name)).toEqual(["user1", "user2"])451 })452453 test("DraftSet in new object set into Map should finalize correctly", () => {454 const baseState = {455 map: new Map([["key1", {items: new Set([1, 2, 3])}]])456 }457458 const result = produce(baseState, draft => {459 const existingItems = draft.map.get("key1").items460 // Create a new plain object containing the draft Set461 const newEntry = {items: existingItems, extra: "data"}462 draft.map.set("key1", newEntry)463 newEntry.items.add(4)464 })465466 // Verify the result is properly finalized (not a draft/proxy)467 const items = result.map.get("key1").items468 expect(items).toBeInstanceOf(Set)469 expect([...items]).toEqual([1, 2, 3, 4])470 expect(result.map.get("key1").extra).toBe("data")471 })472473 // Test for DraftSet.add() with non-draft object containing nested draft474 // This covers the handleCrossReference() call in DraftSet.add()475 test("DraftSet.add() should handle non-draft object containing nested draft", () => {476 const baseState = {477 items: [{id: 1, name: "item1"}],478 itemSet: new Set()479 }480481 const result = produce(baseState, draft => {482 // Get a draft of an existing item483 const draftItem = draft.items[0]484 // Create a new plain object that contains the draft485 const wrapper = {item: draftItem, extra: "wrapper data"}486 // Add the non-draft wrapper (containing a draft) to the Set487 draft.itemSet.add(wrapper)488 // Modify the draft item after adding489 draftItem.name = "modified"490 })491492 // The wrapper should be finalized correctly493 const addedItems = [...result.itemSet]494 expect(addedItems).toHaveLength(1)495 expect(addedItems[0].item.id).toBe(1)496 expect(addedItems[0].item.name).toBe("modified")497 expect(addedItems[0].extra).toBe("wrapper data")498 // Verify it's not a proxy499 expect(() => JSON.stringify(result)).not.toThrow()500 })501502 test("DraftSet.add() should handle deeply nested drafts in plain objects", () => {503 const baseState = {504 nested: {505 deep: {506 value: "original"507 }508 },509 mySet: new Set()510 }511512 const result = produce(baseState, draft => {513 // Get a draft of a deeply nested object514 const deepDraft = draft.nested.deep515 // Create a plain object hierarchy containing the draft516 const wrapper = {517 level1: {518 level2: {519 draftRef: deepDraft520 }521 }522 }523 // Add to Set524 draft.mySet.add(wrapper)525 // Modify the draft526 deepDraft.value = "modified"527 })528529 const items = [...result.mySet]530 expect(items).toHaveLength(1)531 expect(items[0].level1.level2.draftRef.value).toBe("modified")532 // Should not throw when accessing533 expect(() => JSON.stringify(result)).not.toThrow()534 })535})