Skip to content
Myr

readme.js

This file

Path

__tests__/readme.js

266 lines · 5.6 KiB · JavaScript

Last changed by

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

History of this file

Take it

The walk stopped after 200 commits: lines older than 07f5cc9 point at it.

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

line 1why, one step back
1"use strict"

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 2–3why, one step back
2import {
3 produce,

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

lines 4–6why, one step back
4 applyPatches,
5 immerable,6 produceWithPatches,

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 7–8why, one step back
7 enableMapSet,
8 enablePatches,

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

lines 9–11why, one step back
9 setAutoFreeze
10} from "../src/immer"11

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 12–13why, one step back
12enableMapSet()
13enablePatches()

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

lines 14–220why, one step back
14
15describe("readme example", () => {16 it("works", () => {17 const baseState = [18 {19 todo: "Learn typescript",20 done: true21 },22 {23 todo: "Try immer",24 done: false25 }26 ]2728 const nextState = produce(baseState, draft => {29 draft.push({todo: "Tweet about it"})30 draft[1].done = true31 })3233 // the new item is only added to the next state,34 // base state is unmodified35 expect(baseState.length).toBe(2)36 expect(nextState.length).toBe(3)3738 // same for the changed 'done' prop39 expect(baseState[1].done).toBe(false)40 expect(nextState[1].done).toBe(true)4142 // unchanged data is structurally shared43 expect(nextState[0]).toBe(baseState[0])44 // changed data not (dûh)45 expect(nextState[1]).not.toBe(baseState[1])46 })4748 it("patches", () => {49 let state = {50 name: "Micheal",51 age: 3252 }5354 // Let's assume the user is in a wizard, and we don't know whether55 // his changes should be updated56 let fork = state57 // all the changes the user made in the wizard58 let changes = []59 // all the inverse patches60 let inverseChanges = []6162 fork = produce(63 fork,64 draft => {65 draft.age = 3366 },67 // The third argument to produce is a callback to which the patches will be fed68 (patches, inversePatches) => {69 changes.push(...patches)70 inverseChanges.push(...inversePatches)71 }72 )7374 // In the mean time, our original state is updated as well, as changes come in from the server75 state = produce(state, draft => {76 draft.name = "Michel"77 })7879 // When the wizard finishes (successfully) we can replay the changes made in the fork onto the *new* state!80 state = applyPatches(state, changes)8182 // state now contains the changes from both code paths!83 expect(state).toEqual({84 name: "Michel",85 age: 3386 })8788 // Even after finishing the wizard, the user might change his mind...89 state = applyPatches(state, inverseChanges)90 expect(state).toEqual({91 name: "Michel",92 age: 3293 })94 })9596 it("can update set", () => {97 const state = {98 title: "hello",99 tokenSet: new Set()100 }101102 const nextState = produce(state, draft => {103 draft.title = draft.title.toUpperCase()104 draft.tokenSet.add("c1342")105 })106107 expect(state).toEqual({title: "hello", tokenSet: new Set()})108 expect(nextState).toEqual({109 title: "HELLO",110 tokenSet: new Set(["c1342"])111 })112 })113114 it("can deep update map", () => {115 const state = {116 users: new Map([["michel", {name: "miche", age: 27}]])117 }118119 const nextState = produce(state, draft => {120 draft.users.get("michel").name = "michel"121 })122123 expect(state).toEqual({124 users: new Map([["michel", {name: "miche", age: 27}]])125 })126 expect(nextState).toEqual({127 users: new Map([["michel", {name: "michel", age: 27}]])128 })129 })130131 it("supports immerable", () => {132 class Clock {133 constructor(hours = 0, minutes = 0) {134 this.hours = hours135 this.minutes = minutes136 }137138 increment(hours, minutes = 0) {139 return produce(this, d => {140 d.hours += hours141 d.minutes += minutes142 })143 }144145 toString() {146 return `${("" + this.hours).padStart(2, 0)}:${(147 "" + this.minutes148 ).padStart(2, 0)}`149 }150 }151 Clock[immerable] = true152153 const midnight = new Clock()154 const lunch = midnight.increment(12, 30)155156 expect(midnight).not.toBe(lunch)157 expect(lunch).toBeInstanceOf(Clock)158 expect(midnight.toString()).toBe("00:00")159 expect(lunch.toString()).toBe("12:30")160161 const diner = lunch.increment(6)162163 expect(diner).not.toBe(lunch)164 expect(lunch).toBeInstanceOf(Clock)165 expect(diner.toString()).toBe("18:30")166 })167168 test("produceWithPatches", () => {169 const result = produceWithPatches(170 {171 age: 33172 },173 draft => {174 draft.age++175 }176 )177 expect(result).toEqual([178 {179 age: 34180 },181 [182 {183 op: "replace",184 path: ["age"],185 value: 34186 }187 ],188 [189 {190 op: "replace",191 path: ["age"],192 value: 33193 }194 ]195 ])196 })197})198199test("Producers can update Maps", () => {200 setAutoFreeze(true)201 const usersById_v1 = new Map()202203 const usersById_v2 = produce(usersById_v1, draft => {204 // Modifying a map results in a new map205 draft.set("michel", {name: "Michel Weststrate", country: "NL"})206 })207208 const usersById_v3 = produce(usersById_v2, draft => {209 // Making a change deep inside a map, results in a new map as well!210 draft.get("michel").country = "UK"211 debugger212 })213214 // We got a new map each time!215 expect(usersById_v2).not.toBe(usersById_v1)216 expect(usersById_v3).not.toBe(usersById_v2)217 // With different content obviously218 expect(usersById_v1).toMatchInlineSnapshot(`Map {}`)219 expect(usersById_v2).toMatchInlineSnapshot(`220 Map {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 221why, one step back
221 "michel" => {

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

lines 222–228why, one step back
222 "country": "NL",
223 "name": "Michel Weststrate",224 },225 }226 `)227 expect(usersById_v3).toMatchInlineSnapshot(`228 Map {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 229why, one step back
229 "michel" => {

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

lines 230–266why, one step back
230 "country": "UK",
231 "name": "Michel Weststrate",232 },233 }234 `)235 // The old one was never modified236 expect(usersById_v1.size).toBe(0)237 // And trying to change a Map outside a producers is going to: NO!238 expect(() => usersById_v3.clear()).toThrowErrorMatchingSnapshot()239})240241test("clock class", () => {242 class Clock {243 [immerable] = true244245 constructor(hour, minute) {246 this.hour = hour247 this.minute = minute248 }249250 get time() {251 return `${this.hour}:${this.minute}`252 }253254 tick() {255 return produce(this, draft => {256 draft.minute++257 })258 }259 }260261 const clock1 = new Clock(12, 10)262 const clock2 = clock1.tick()263 expect(clock1.time).toEqual("12:10") // 12:10264 expect(clock2.time).toEqual("12:11") // 12:11265 expect(clock2).toBeInstanceOf(Clock)266})