-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
persistSync.test.tsx
741 lines (645 loc) · 19.4 KB
/
persistSync.test.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
import { afterEach, describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import { replacer, reviver } from './test-utils'
const createPersistentStore = (initialValue: string | null) => {
let state = initialValue
const getItem = (): string | null => {
getItemSpy()
return state
}
const setItem = (name: string, newState: string) => {
setItemSpy(name, newState)
state = newState
}
const removeItem = (name: string) => {
removeItemSpy(name)
state = null
}
const getItemSpy = vi.fn()
const setItemSpy = vi.fn()
const removeItemSpy = vi.fn()
return {
storage: { getItem, setItem, removeItem },
getItemSpy,
setItemSpy,
}
}
describe('persist middleware with sync configuration', () => {
const consoleError = console.error
afterEach(() => {
console.error = consoleError
})
it('can rehydrate state', () => {
const storage = {
getItem: (name: string) =>
JSON.stringify({
state: { count: 42, name },
version: 0,
}),
setItem: () => {},
removeItem: () => {},
}
const onRehydrateStorageSpy = vi.fn()
const useBoundStore = create(
persist(
() => ({
count: 0,
name: 'empty',
}),
{
name: 'test-storage',
storage: createJSONStorage(() => storage),
onRehydrateStorage: () => onRehydrateStorageSpy,
},
),
)
expect(useBoundStore.getState()).toEqual({
count: 42,
name: 'test-storage',
})
expect(onRehydrateStorageSpy).toBeCalledWith(
{ count: 42, name: 'test-storage' },
undefined,
)
})
it('can throw rehydrate error', () => {
const storage = {
getItem: () => {
throw new Error('getItem error')
},
setItem: () => {},
removeItem: () => {},
}
const spy = vi.fn()
create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
onRehydrateStorage: () => spy,
}),
)
expect(spy).toBeCalledWith(undefined, new Error('getItem error'))
})
it('can persist state', () => {
const { storage, setItemSpy } = createPersistentStore(null)
const createStore = () => {
const onRehydrateStorageSpy = vi.fn()
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
onRehydrateStorage: () => onRehydrateStorageSpy,
}),
)
return { useBoundStore, onRehydrateStorageSpy }
}
// Initialize from empty storage
const { useBoundStore, onRehydrateStorageSpy } = createStore()
expect(useBoundStore.getState()).toEqual({ count: 0 })
expect(onRehydrateStorageSpy).toBeCalledWith({ count: 0 }, undefined)
// Write something to the store
useBoundStore.setState({ count: 42 })
expect(useBoundStore.getState()).toEqual({ count: 42 })
expect(setItemSpy).toBeCalledWith(
'test-storage',
JSON.stringify({ state: { count: 42 }, version: 0 }),
)
// Create the same store a second time and check if the persisted state
// is loaded correctly
const {
useBoundStore: useBoundStore2,
onRehydrateStorageSpy: onRehydrateStorageSpy2,
} = createStore()
expect(useBoundStore2.getState()).toEqual({ count: 42 })
expect(onRehydrateStorageSpy2).toBeCalledWith({ count: 42 }, undefined)
})
it('can migrate persisted state', () => {
const setItemSpy = vi.fn()
const onRehydrateStorageSpy = vi.fn()
const migrateSpy = vi.fn(() => ({ count: 99 }))
const storage = {
getItem: () =>
JSON.stringify({
state: { count: 42 },
version: 12,
}),
setItem: setItemSpy,
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
version: 13,
storage: createJSONStorage(() => storage),
onRehydrateStorage: () => onRehydrateStorageSpy,
migrate: migrateSpy,
}),
)
expect(useBoundStore.getState()).toEqual({ count: 99 })
expect(migrateSpy).toBeCalledWith({ count: 42 }, 12)
expect(setItemSpy).toBeCalledWith(
'test-storage',
JSON.stringify({
state: { count: 99 },
version: 13,
}),
)
expect(onRehydrateStorageSpy).toBeCalledWith({ count: 99 }, undefined)
})
it('can correclty handle a missing migrate function', () => {
console.error = vi.fn()
const onRehydrateStorageSpy = vi.fn()
const storage = {
getItem: () =>
JSON.stringify({
state: { count: 42 },
version: 12,
}),
setItem: (_: string, _value: string) => {},
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
version: 13,
storage: createJSONStorage(() => storage),
onRehydrateStorage: () => onRehydrateStorageSpy,
}),
)
expect(useBoundStore.getState()).toEqual({ count: 0 })
expect(console.error).toHaveBeenCalled()
expect(onRehydrateStorageSpy).toBeCalledWith({ count: 0 }, undefined)
})
it('can throw migrate error', () => {
const onRehydrateStorageSpy = vi.fn()
const storage = {
getItem: () =>
JSON.stringify({
state: {},
version: 12,
}),
setItem: () => {},
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
version: 13,
storage: createJSONStorage(() => storage),
migrate: () => {
throw new Error('migrate error')
},
onRehydrateStorage: () => onRehydrateStorageSpy,
}),
)
expect(useBoundStore.getState()).toEqual({ count: 0 })
expect(onRehydrateStorageSpy).toBeCalledWith(
undefined,
new Error('migrate error'),
)
})
it('passes the latest state to onRehydrateStorage and onHydrate on first hydrate', () => {
const onRehydrateStorageSpy = vi.fn()
const storage = {
getItem: () => JSON.stringify({ state: { count: 1 } }),
setItem: () => {},
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
onRehydrateStorage: onRehydrateStorageSpy,
}),
)
/**
* NOTE: It's currently not possible to add an 'onHydrate' listener which will be
* invoked prior to the first hydration. This is because, during first hydration,
* the 'onHydrate' listener set (which will be empty) is evaluated before the
* 'persist' API is exposed to the caller of 'create'/'createStore'.
*
* const onHydrateSpy = vi.fn()
* useBoundStore.persist.onHydrate(onHydrateSpy)
* expect(onHydrateSpy).toBeCalledWith({ count: 0 })
*/
// The 'onRehydrateStorage' and 'onHydrate' spies are invoked prior to rehydration,
// so they should both be passed the default state.
expect(onRehydrateStorageSpy).toBeCalledWith({ count: 0 })
expect(useBoundStore.getState()).toEqual({ count: 1 })
})
it('gives the merged state to onRehydrateStorage', () => {
const onRehydrateStorageSpy = vi.fn()
const storage = {
getItem: () =>
JSON.stringify({
state: { count: 1 },
version: 0,
}),
setItem: () => {},
removeItem: () => {},
}
const unstorableMethod = () => {}
const useBoundStore = create(
persist(() => ({ count: 0, unstorableMethod }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
onRehydrateStorage: () => onRehydrateStorageSpy,
}),
)
const expectedState = { count: 1, unstorableMethod }
expect(useBoundStore.getState()).toEqual(expectedState)
expect(onRehydrateStorageSpy).toBeCalledWith(expectedState, undefined)
})
it('can custom merge the stored state', () => {
const storage = {
getItem: () =>
JSON.stringify({
state: {
count: 1,
actions: {},
},
version: 0,
}),
setItem: () => {},
removeItem: () => {},
}
const unstorableMethod = () => {}
const useBoundStore = create(
persist(() => ({ count: 0, actions: { unstorableMethod } }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
merge: (_persistedState, currentState) => {
const persistedState = _persistedState as any
delete persistedState.actions
return {
...currentState,
...persistedState,
}
},
}),
)
expect(useBoundStore.getState()).toEqual({
count: 1,
actions: {
unstorableMethod,
},
})
})
it("can merge the state when the storage item doesn't have a version", () => {
const storage = {
getItem: () =>
JSON.stringify({
state: {
count: 1,
},
}),
setItem: () => {},
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
}),
)
expect(useBoundStore.getState()).toEqual({
count: 1,
})
})
it('can filter the persisted value', () => {
const setItemSpy = vi.fn()
const storage = {
getItem: () => '',
setItem: setItemSpy,
removeItem: () => {},
}
const useBoundStore = create(
persist(
() => ({
object: {
first: '0',
second: '1',
},
array: [
{
value: '0',
},
{
value: '1',
},
{
value: '2',
},
],
}),
{
name: 'test-storage',
storage: createJSONStorage(() => storage),
partialize: (state) => {
return {
object: {
first: state.object.first,
},
array: state.array.filter((e) => e.value !== '1'),
}
},
},
),
)
useBoundStore.setState({})
expect(setItemSpy).toBeCalledWith(
'test-storage',
JSON.stringify({
state: {
object: {
first: '0',
},
array: [
{
value: '0',
},
{
value: '2',
},
],
},
version: 0,
}),
)
})
it('can access the options through the api', () => {
const storage = {
getItem: () => null,
setItem: vi.fn(),
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
}),
)
expect(useBoundStore.persist.getOptions().name).toBeDefined()
expect(useBoundStore.persist.getOptions().name).toBe('test-storage')
})
it('can change the options through the api', () => {
const setItemSpy = vi.fn()
const storage = {
getItem: () => null,
setItem: setItemSpy,
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
partialize: (s) => s as Partial<typeof s>,
}),
)
useBoundStore.setState({})
expect(setItemSpy).toBeCalledWith(
'test-storage',
'{"state":{"count":0},"version":0}',
)
useBoundStore.persist.setOptions({
name: 'test-storage-2',
partialize: (state) =>
Object.fromEntries(
Object.entries(state).filter(([key]) => key !== 'count'),
),
})
useBoundStore.setState({})
expect(setItemSpy).toBeCalledWith(
'test-storage-2',
'{"state":{},"version":0}',
)
})
it('can clear the storage through the api', () => {
const removeItemSpy = vi.fn()
const storage = {
getItem: () => null,
setItem: () => {},
removeItem: removeItemSpy,
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
}),
)
useBoundStore.persist.clearStorage()
expect(removeItemSpy).toBeCalledWith('test-storage')
})
it('can manually rehydrate through the api', () => {
const storageValue = '{"state":{"count":1},"version":0}'
const storage = {
getItem: () => '',
setItem: () => {},
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
}),
)
storage.getItem = () => storageValue
useBoundStore.persist.rehydrate()
expect(useBoundStore.getState()).toEqual({
count: 1,
})
})
it('can check if the store has been hydrated through the api', async () => {
const storage = {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
}),
)
expect(useBoundStore.persist.hasHydrated()).toBe(true)
await useBoundStore.persist.rehydrate()
expect(useBoundStore.persist.hasHydrated()).toBe(true)
})
it('can wait for rehydration through the api', async () => {
const storageValue1 = '{"state":{"count":1},"version":0}'
const storageValue2 = '{"state":{"count":2},"version":0}'
const onHydrateSpy1 = vi.fn()
const onHydrateSpy2 = vi.fn()
const onFinishHydrationSpy1 = vi.fn()
const onFinishHydrationSpy2 = vi.fn()
const storage = {
getItem: () => '',
setItem: () => {},
removeItem: () => {},
}
const useBoundStore = create(
persist(() => ({ count: 0 }), {
name: 'test-storage',
storage: createJSONStorage(() => storage),
}),
)
const hydrateUnsub1 = useBoundStore.persist.onHydrate(onHydrateSpy1)
useBoundStore.persist.onHydrate(onHydrateSpy2)
const finishHydrationUnsub1 = useBoundStore.persist.onFinishHydration(
onFinishHydrationSpy1,
)
useBoundStore.persist.onFinishHydration(onFinishHydrationSpy2)
storage.getItem = () => storageValue1
await useBoundStore.persist.rehydrate()
expect(onHydrateSpy1).toBeCalledWith({ count: 0 })
expect(onHydrateSpy2).toBeCalledWith({ count: 0 })
expect(onFinishHydrationSpy1).toBeCalledWith({ count: 1 })
expect(onFinishHydrationSpy2).toBeCalledWith({ count: 1 })
hydrateUnsub1()
finishHydrationUnsub1()
storage.getItem = () => storageValue2
await useBoundStore.persist.rehydrate()
expect(onHydrateSpy1).not.toBeCalledTimes(2)
expect(onHydrateSpy2).toBeCalledWith({ count: 1 })
expect(onFinishHydrationSpy1).not.toBeCalledTimes(2)
expect(onFinishHydrationSpy2).toBeCalledWith({ count: 2 })
})
it('can skip initial hydration', async () => {
const storage = {
getItem: (name: string) => ({
state: { count: 42, name },
version: 0,
}),
setItem: () => {},
removeItem: () => {},
}
const onRehydrateStorageSpy = vi.fn()
const useBoundStore = create(
persist(
() => ({
count: 0,
name: 'empty',
}),
{
name: 'test-storage',
storage: storage,
onRehydrateStorage: () => onRehydrateStorageSpy,
skipHydration: true,
},
),
)
expect(useBoundStore.getState()).toEqual({
count: 0,
name: 'empty',
})
// Because `skipHydration` is only in newImpl and the hydration function for newImpl is now a promise
// In the default case we would need to await `onFinishHydration` to assert the auto hydration has completed
// As we are testing the skip hydration case we await nextTick, to make sure the store is initialised
await new Promise((resolve) => process.nextTick(resolve))
// Asserting store hasn't hydrated from nextTick
expect(useBoundStore.persist.hasHydrated()).toBe(false)
await useBoundStore.persist.rehydrate()
expect(useBoundStore.getState()).toEqual({
count: 42,
name: 'test-storage',
})
expect(onRehydrateStorageSpy).toBeCalledWith(
{ count: 42, name: 'test-storage' },
undefined,
)
})
it('handles state updates during onRehydrateStorage', () => {
const storage = {
getItem: () => JSON.stringify({ state: { count: 1 } }),
setItem: () => {},
removeItem: () => {},
}
const useBoundStore = create<{ count: number; inc: () => void }>()(
persist(
(set) => ({
count: 0,
inc: () => set((s) => ({ count: s.count + 1 })),
}),
{
name: 'test-storage',
storage: createJSONStorage(() => storage),
onRehydrateStorage: () => (s) => s?.inc(),
},
),
)
expect(useBoundStore.getState().count).toEqual(2)
})
it('can rehydrate state with custom deserialized Map', () => {
const storage = {
getItem: () =>
JSON.stringify({
map: { type: 'Map', value: [['foo', 'bar']] },
}),
setItem: () => {},
removeItem: () => {},
}
const map = new Map()
const onRehydrateStorageSpy = vi.fn()
const useBoundStore = create(
persist(
() => ({
map,
}),
{
name: 'test-storage',
storage: createJSONStorage(() => storage),
onRehydrateStorage: () => onRehydrateStorageSpy,
},
),
)
const updatedMap = map.set('foo', 'bar')
expect(useBoundStore.getState()).toEqual({
map: updatedMap,
})
expect(onRehydrateStorageSpy).toBeCalledWith({ map: updatedMap }, undefined)
})
it('can persist state with custom serialization of Map', () => {
const { storage, setItemSpy } = createPersistentStore(null)
const map = new Map()
const createStore = () => {
const onRehydrateStorageSpy = vi.fn()
const useBoundStore = create(
persist(() => ({ map }), {
name: 'test-storage',
storage: createJSONStorage(() => storage, { replacer, reviver }),
onRehydrateStorage: () => onRehydrateStorageSpy,
}),
)
return { useBoundStore, onRehydrateStorageSpy }
}
// Initialize from empty storage
const { useBoundStore, onRehydrateStorageSpy } = createStore()
expect(useBoundStore.getState()).toEqual({ map })
expect(onRehydrateStorageSpy).toBeCalledWith({ map }, undefined)
// Write something to the store
const updatedMap = map.set('foo', 'bar')
useBoundStore.setState({ map: updatedMap })
expect(useBoundStore.getState()).toEqual({
map: updatedMap,
})
expect(setItemSpy).toBeCalledWith(
'test-storage',
JSON.stringify({
state: { map: { type: 'Map', value: [['foo', 'bar']] } },
version: 0,
}),
)
// Create the same store a second time and check if the persisted state
// is loaded correctly
const {
useBoundStore: useBoundStore2,
onRehydrateStorageSpy: onRehydrateStorageSpy2,
} = createStore()
expect(useBoundStore2.getState()).toEqual({ map: updatedMap })
expect(onRehydrateStorageSpy2).toBeCalledWith(
{ map: updatedMap },
undefined,
)
})
})