-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathcreateSlice.test.ts
1303 lines (1175 loc) · 38.9 KB
/
createSlice.test.ts
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { vi } from 'vitest'
import type { Draft, Patch } from 'immer'
import { applyPatches, enablePatches, produceWithPatches } from 'immer'
import type {
Action,
CaseReducer,
CaseReducerDefinition,
CreatorCaseReducers,
PayloadAction,
PayloadActionCreator,
ReducerCreator,
ReducerCreatorEntry,
ReducerCreators,
ReducerDefinition,
ReducerHandlingContext,
SliceActionType,
ThunkAction,
WithSlice,
} from '@reduxjs/toolkit'
import {
buildCreateSlice,
combineSlices,
configureStore,
createAction,
createNextState,
createSlice,
isAnyOf,
nanoid,
preparedReducerCreator,
reducerCreator,
} from '@reduxjs/toolkit'
import {
createConsole,
getLog,
mockConsole,
} from 'console-testing-library/pure'
import type { IfMaybeUndefined, NoInfer } from '../tsHelpers'
enablePatches()
type CreateSlice = typeof createSlice
const loaderCreatorType = Symbol('loaderCreatorType')
const historyMethodsCreatorType = Symbol('historyMethodsCreatorType')
const undoableCreatorType = Symbol('undoableCreatorType')
const patchCreatorType = Symbol('patchCreatorType')
describe('createSlice', () => {
let restore: () => void
beforeEach(() => {
restore = mockConsole(createConsole())
})
describe('when slice is undefined', () => {
it('should throw an error', () => {
expect(() =>
// @ts-ignore
createSlice({
reducers: {
increment: (state) => state + 1,
multiply: (state, action: PayloadAction<number>) =>
state * action.payload,
},
initialState: 0,
}),
).toThrowError()
})
})
describe('when slice is an empty string', () => {
it('should throw an error', () => {
expect(() =>
createSlice({
name: '',
reducers: {
increment: (state) => state + 1,
multiply: (state, action: PayloadAction<number>) =>
state * action.payload,
},
initialState: 0,
}),
).toThrowError()
})
})
describe('when initial state is undefined', () => {
beforeEach(() => {
vi.stubEnv('NODE_ENV', 'development')
return vi.unstubAllEnvs
})
it('should throw an error', () => {
createSlice({
name: 'test',
reducers: {},
initialState: undefined,
})
expect(getLog().log).toBe(
'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`',
)
})
})
describe('when passing slice', () => {
const { actions, reducer, caseReducers } = createSlice({
reducers: {
increment: (state) => state + 1,
},
initialState: 0,
name: 'cool',
})
it('should create increment action', () => {
expect(actions.hasOwnProperty('increment')).toBe(true)
})
it('should have the correct action for increment', () => {
expect(actions.increment()).toEqual({
type: 'cool/increment',
payload: undefined,
})
})
it('should return the correct value from reducer', () => {
expect(reducer(undefined, actions.increment())).toEqual(1)
})
it('should include the generated case reducers', () => {
expect(caseReducers).toBeTruthy()
expect(caseReducers.increment).toBeTruthy()
expect(typeof caseReducers.increment).toBe('function')
})
it('getInitialState should return the state', () => {
const initialState = 42
const slice = createSlice({
name: 'counter',
initialState,
reducers: {},
})
expect(slice.getInitialState()).toBe(initialState)
})
it('should allow non-draftable initial state', () => {
expect(() =>
createSlice({
name: 'params',
initialState: new URLSearchParams(),
reducers: {},
}),
).not.toThrowError()
})
})
describe('when initialState is a function', () => {
const initialState = () => ({ user: '' })
const { actions, reducer } = createSlice({
reducers: {
setUserName: (state, action) => {
state.user = action.payload
},
},
initialState,
name: 'user',
})
it('should set the username', () => {
expect(reducer(undefined, actions.setUserName('eric'))).toEqual({
user: 'eric',
})
})
it('getInitialState should return the state', () => {
const initialState = () => 42
const slice = createSlice({
name: 'counter',
initialState,
reducers: {},
})
expect(slice.getInitialState()).toBe(42)
})
it('should allow non-draftable initial state', () => {
expect(() =>
createSlice({
name: 'params',
initialState: () => new URLSearchParams(),
reducers: {},
}),
).not.toThrowError()
})
})
describe('when mutating state object', () => {
const initialState = { user: '' }
const { actions, reducer } = createSlice({
reducers: {
setUserName: (state, action) => {
state.user = action.payload
},
},
initialState,
name: 'user',
})
it('should set the username', () => {
expect(reducer(initialState, actions.setUserName('eric'))).toEqual({
user: 'eric',
})
})
})
describe('when passing extra reducers', () => {
const addMore = createAction<{ amount: number }>('ADD_MORE')
const { reducer } = createSlice({
name: 'test',
reducers: {
increment: (state) => state + 1,
multiply: (state, action) => state * action.payload,
},
extraReducers: (builder) => {
builder.addCase(
addMore,
(state, action) => state + action.payload.amount,
)
},
initialState: 0,
})
it('should call extra reducers when their actions are dispatched', () => {
const result = reducer(10, addMore({ amount: 5 }))
expect(result).toBe(15)
})
describe('builder callback for extraReducers', () => {
const increment = createAction<number, 'increment'>('increment')
test('can be used with actionCreators', () => {
const slice = createSlice({
name: 'counter',
initialState: 0,
reducers: {},
extraReducers: (builder) =>
builder.addCase(
increment,
(state, action) => state + action.payload,
),
})
expect(slice.reducer(0, increment(5))).toBe(5)
})
test('can be used with string action types', () => {
const slice = createSlice({
name: 'counter',
initialState: 0,
reducers: {},
extraReducers: (builder) =>
builder.addCase(
'increment',
(state, action: { type: 'increment'; payload: number }) =>
state + action.payload,
),
})
expect(slice.reducer(0, increment(5))).toBe(5)
})
test('prevents the same action type from being specified twice', () => {
expect(() => {
const slice = createSlice({
name: 'counter',
initialState: 0,
reducers: {},
extraReducers: (builder) =>
builder
.addCase('increment', (state) => state + 1)
.addCase('increment', (state) => state + 1),
})
slice.reducer(undefined, { type: 'unrelated' })
}).toThrowErrorMatchingInlineSnapshot(
`[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
)
})
test('can be used with addMatcher and type guard functions', () => {
const slice = createSlice({
name: 'counter',
initialState: 0,
reducers: {},
extraReducers: (builder) =>
builder.addMatcher(
increment.match,
(state, action: { type: 'increment'; payload: number }) =>
state + action.payload,
),
})
expect(slice.reducer(0, increment(5))).toBe(5)
})
test('can be used with addDefaultCase', () => {
const slice = createSlice({
name: 'counter',
initialState: 0,
reducers: {},
extraReducers: (builder) =>
builder.addDefaultCase(
(state, action) =>
state + (action as PayloadAction<number>).payload,
),
})
expect(slice.reducer(0, increment(5))).toBe(5)
})
// for further tests, see the test of createReducer that goes way more into depth on this
})
})
describe('behavior with enhanced case reducers', () => {
it('should pass all arguments to the prepare function', () => {
const prepare = vi.fn((payload, somethingElse) => ({ payload }))
const testSlice = createSlice({
name: 'test',
initialState: 0,
reducers: {
testReducer: {
reducer: (s) => s,
prepare,
},
},
})
expect(testSlice.actions.testReducer('a', 1)).toEqual({
type: 'test/testReducer',
payload: 'a',
})
expect(prepare).toHaveBeenCalledWith('a', 1)
})
it('should call the reducer function', () => {
const reducer = vi.fn(() => 5)
const testSlice = createSlice({
name: 'test',
initialState: 0,
reducers: {
testReducer: {
reducer,
prepare: (payload: any) => ({ payload }),
},
},
})
testSlice.reducer(0, testSlice.actions.testReducer('testPayload'))
expect(reducer).toHaveBeenCalledWith(
0,
expect.objectContaining({ payload: 'testPayload' }),
)
})
})
describe('circularity', () => {
test('extraReducers can reference each other circularly', () => {
const first = createSlice({
name: 'first',
initialState: 'firstInitial',
reducers: {
something() {
return 'firstSomething'
},
},
extraReducers(builder) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
builder.addCase(second.actions.other, () => {
return 'firstOther'
})
},
})
const second = createSlice({
name: 'second',
initialState: 'secondInitial',
reducers: {
other() {
return 'secondOther'
},
},
extraReducers(builder) {
builder.addCase(first.actions.something, () => {
return 'secondSomething'
})
},
})
expect(first.reducer(undefined, { type: 'unrelated' })).toBe(
'firstInitial',
)
expect(first.reducer(undefined, first.actions.something())).toBe(
'firstSomething',
)
expect(first.reducer(undefined, second.actions.other())).toBe(
'firstOther',
)
expect(second.reducer(undefined, { type: 'unrelated' })).toBe(
'secondInitial',
)
expect(second.reducer(undefined, first.actions.something())).toBe(
'secondSomething',
)
expect(second.reducer(undefined, second.actions.other())).toBe(
'secondOther',
)
})
})
describe('Deprecation warnings', () => {
let originalNodeEnv = process.env.NODE_ENV
beforeEach(() => {
vi.resetModules()
restore = mockConsole(createConsole())
})
afterEach(() => {
process.env.NODE_ENV = originalNodeEnv
})
// NOTE: This needs to be in front of the later `createReducer` call to check the one-time warning
it('Throws an error if the legacy object notation is used', async () => {
const { createSlice } = await import('../createSlice')
let dummySlice = (createSlice as CreateSlice)({
name: 'dummy',
initialState: [],
reducers: {},
extraReducers: {
// @ts-ignore
a: () => [],
},
})
let reducer: any
// Have to trigger the lazy creation
const wrapper = () => {
reducer = dummySlice.reducer
reducer(undefined, { type: 'dummy' })
}
expect(wrapper).toThrowError(
/The object notation for `createSlice.extraReducers` has been removed/,
)
dummySlice = (createSlice as CreateSlice)({
name: 'dummy',
initialState: [],
reducers: {},
extraReducers: {
// @ts-ignore
a: () => [],
},
})
expect(wrapper).toThrowError(
/The object notation for `createSlice.extraReducers` has been removed/,
)
})
// TODO Determine final production behavior here
it.todo('Crashes in production', () => {
vi.stubEnv('NODE_ENV', 'production')
const { createSlice } = require('../createSlice')
const dummySlice = (createSlice as CreateSlice)({
name: 'dummy',
initialState: [],
reducers: {},
// @ts-ignore
extraReducers: {},
})
const wrapper = () => {
const { reducer } = dummySlice
reducer(undefined, { type: 'dummy' })
}
expect(wrapper).toThrowError(
/The object notation for `createSlice.extraReducers` has been removed/,
)
vi.unstubAllEnvs()
})
})
describe('slice selectors', () => {
const slice = createSlice({
name: 'counter',
initialState: 42,
reducers: {},
selectors: {
selectSlice: (state) => state,
selectMultiple: Object.assign(
(state: number, multiplier: number) => state * multiplier,
{ test: 0 },
),
},
})
it('expects reducer under slice.reducerPath if no selectState callback passed', () => {
const testState = {
[slice.reducerPath]: slice.getInitialState(),
}
const { selectSlice, selectMultiple } = slice.selectors
expect(selectSlice(testState)).toBe(slice.getInitialState())
expect(selectMultiple(testState, 2)).toBe(slice.getInitialState() * 2)
})
it('allows passing a selector for a custom location', () => {
const customState = {
number: slice.getInitialState(),
}
const { selectSlice, selectMultiple } = slice.getSelectors(
(state: typeof customState) => state.number,
)
expect(selectSlice(customState)).toBe(slice.getInitialState())
expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2)
})
it('allows accessing properties on the selector', () => {
expect(slice.selectors.selectMultiple.unwrapped.test).toBe(0)
})
it('has selectSlice attached to slice, which can go without this', () => {
const slice = createSlice({
name: 'counter',
initialState: 42,
reducers: {},
})
const { selectSlice } = slice
expect(() => selectSlice({ counter: 42 })).not.toThrow()
expect(selectSlice({ counter: 42 })).toBe(42)
})
})
describe('slice injections', () => {
it('uses injectInto to inject slice into combined reducer', () => {
const slice = createSlice({
name: 'counter',
initialState: 42,
reducers: {
increment: (state) => ++state,
},
selectors: {
selectMultiple: (state, multiplier: number) => state * multiplier,
},
})
const { increment } = slice.actions
const combinedReducer = combineSlices({
static: slice.reducer,
}).withLazyLoadedSlices<WithSlice<typeof slice>>()
const uninjectedState = combinedReducer(undefined, increment())
expect(uninjectedState.counter).toBe(undefined)
const injectedSlice = slice.injectInto(combinedReducer)
// selector returns initial state if undefined in real state
expect(injectedSlice.selectSlice(uninjectedState)).toBe(
slice.getInitialState(),
)
expect(injectedSlice.selectors.selectMultiple({}, 1)).toBe(
slice.getInitialState(),
)
expect(injectedSlice.getSelectors().selectMultiple(undefined, 1)).toBe(
slice.getInitialState(),
)
const injectedState = combinedReducer(undefined, increment())
expect(injectedSlice.selectSlice(injectedState)).toBe(
slice.getInitialState() + 1,
)
expect(injectedSlice.selectors.selectMultiple(injectedState, 1)).toBe(
slice.getInitialState() + 1,
)
})
it('allows providing a custom name to inject under', () => {
const slice = createSlice({
name: 'counter',
reducerPath: 'injected',
initialState: 42,
reducers: {
increment: (state) => ++state,
},
selectors: {
selectMultiple: (state, multiplier: number) => state * multiplier,
},
})
const { increment } = slice.actions
const combinedReducer = combineSlices({
static: slice.reducer,
}).withLazyLoadedSlices<WithSlice<typeof slice> & { injected2: number }>()
const uninjectedState = combinedReducer(undefined, increment())
expect(uninjectedState.injected).toBe(undefined)
const injected = slice.injectInto(combinedReducer)
const injectedState = combinedReducer(undefined, increment())
expect(injected.selectSlice(injectedState)).toBe(
slice.getInitialState() + 1,
)
expect(injected.selectors.selectMultiple(injectedState, 2)).toBe(
(slice.getInitialState() + 1) * 2,
)
const injected2 = slice.injectInto(combinedReducer, {
reducerPath: 'injected2',
})
const injected2State = combinedReducer(undefined, increment())
expect(injected2.selectSlice(injected2State)).toBe(
slice.getInitialState() + 1,
)
expect(injected2.selectors.selectMultiple(injected2State, 2)).toBe(
(slice.getInitialState() + 1) * 2,
)
})
it('avoids incorrectly caching selectors', () => {
const slice = createSlice({
name: 'counter',
reducerPath: 'injected',
initialState: 42,
reducers: {
increment: (state) => ++state,
},
selectors: {
selectMultiple: (state, multiplier: number) => state * multiplier,
},
})
expect(slice.getSelectors()).toBe(slice.getSelectors())
const combinedReducer = combineSlices({
static: slice.reducer,
}).withLazyLoadedSlices<WithSlice<typeof slice>>()
const injected = slice.injectInto(combinedReducer)
expect(injected.getSelectors()).not.toBe(slice.getSelectors())
expect(injected.getSelectors().selectMultiple(undefined, 1)).toBe(42)
expect(() =>
// @ts-expect-error
slice.getSelectors().selectMultiple(undefined, 1),
).toThrowErrorMatchingInlineSnapshot(
`[Error: selectState returned undefined for an uninjected slice reducer]`,
)
const injected2 = slice.injectInto(combinedReducer, {
reducerPath: 'other',
})
// can use same cache for localised selectors
expect(injected.getSelectors()).toBe(injected2.getSelectors())
// these should be different
expect(injected.selectors).not.toBe(injected2.selectors)
})
})
test('reducer and preparedReducer creators can be invoked for object syntax', () => {
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
incrementBy: reducerCreator.create<number>(
(state, action) => state + action.payload,
),
decrementBy: preparedReducerCreator.create(
(amount: number) => ({
payload: amount,
}),
(state, action) => state - action.payload,
),
},
})
const { incrementBy, decrementBy } = counterSlice.actions
expect(counterSlice.reducer(0, incrementBy(1))).toBe(1)
expect(counterSlice.reducer(0, decrementBy(3))).toBe(-3)
})
describe('custom slice reducer creators', () => {
const loaderCreator: ReducerCreator<typeof loaderCreatorType> = {
type: loaderCreatorType,
create(reducers) {
return {
_reducerDefinitionType: loaderCreatorType,
...reducers,
}
},
handle({ reducerName, type }, { started, ended }, context) {
const startedAction = createAction<string>(type + '/started')
const endedAction = createAction<string>(type + '/ended')
function thunkCreator(): ThunkAction<
{ loaderId: string; end: () => void },
unknown,
unknown,
Action
> {
return (dispatch) => {
const loaderId = nanoid()
dispatch(startedAction(loaderId))
return {
loaderId,
end: () => {
dispatch(endedAction(loaderId))
},
}
}
}
Object.assign(thunkCreator, {
started: startedAction,
ended: endedAction,
})
if (started) context.addCase(startedAction, started)
if (ended) context.addCase(endedAction, ended)
context.exposeAction(thunkCreator)
context.exposeCaseReducer({ started, ended })
},
}
test('allows passing custom reducer creators, which can add actions and case reducers', () => {
expect(() =>
createSlice({
name: 'loader',
initialState: {} as Partial<Record<string, true>>,
reducers: () => ({
addLoader: loaderCreator.create({}),
}),
}),
).toThrowErrorMatchingInlineSnapshot(
`[Error: Unsupported reducer type: Symbol(loaderCreatorType)]`,
)
const createAppSlice = buildCreateSlice({
creators: { loader: loaderCreator },
})
const loaderSlice = createAppSlice({
name: 'loader',
initialState: {} as Partial<Record<string, true>>,
reducers: (create) => ({
addLoader: create.loader({
started: (state, { payload }) => {
state[payload] = true
},
ended: (state, { payload }) => {
delete state[payload]
},
}),
}),
selectors: {
selectLoader: (state, id: string) => state[id],
},
})
const { addLoader } = loaderSlice.actions
const { selectLoader } = loaderSlice.selectors
expect(addLoader).toEqual(expect.any(Function))
expect(addLoader.started).toEqual(expect.any(Function))
expect(addLoader.started.type).toBe('loader/addLoader/started')
const isLoaderAction = isAnyOf(addLoader.started, addLoader.ended)
const store = configureStore({
reducer: {
[loaderSlice.reducerPath]: loaderSlice.reducer,
actions: (state: PayloadAction<string>[] = [], action) =>
isLoaderAction(action) ? [...state, action] : state,
},
})
expect(loaderSlice.selectSlice(store.getState())).toEqual({})
const { loaderId, end } = store.dispatch(addLoader())
expect(selectLoader(store.getState(), loaderId)).toBe(true)
end()
expect(selectLoader(store.getState(), loaderId)).toBe(undefined)
expect(store.getState().actions).toEqual([
addLoader.started(loaderId),
addLoader.ended(loaderId),
])
})
describe('creators can return multiple definitions to be spread, or something else entirely', () => {
function getInitialHistoryState<T>(initialState: T): HistoryState<T> {
return {
past: [],
present: initialState,
future: [],
}
}
const historyMethodsCreator: ReducerCreator<
typeof historyMethodsCreatorType
> = {
type: historyMethodsCreatorType,
create() {
return {
undo: this.reducer((state: HistoryState<unknown>) => {
const historyEntry = state.past.pop()
if (historyEntry) {
applyPatches(state, historyEntry.undo)
state.future.unshift(historyEntry)
}
}),
redo: this.reducer((state: HistoryState<unknown>) => {
const historyEntry = state.future.shift()
if (historyEntry) {
applyPatches(state, historyEntry.redo)
state.past.push(historyEntry)
}
}),
reset: {
_reducerDefinitionType: historyMethodsCreatorType,
type: 'reset',
},
}
},
handle(details, definition, context) {
if (definition.type !== 'reset') {
throw new Error('unrecognised definition')
}
reducerCreator.handle(
details,
reducerCreator.create(() => context.getInitialState()),
context,
)
},
}
const undoableCreator: ReducerCreator<typeof undoableCreatorType> = {
type: undoableCreatorType,
create: Object.assign(
function makeUndoable<A extends Action & { meta?: UndoableOptions }>(
reducer: CaseReducer<any, A>,
): CaseReducer<HistoryState<any>, A> {
return (state, action) => {
const [nextState, redoPatch, undoPatch] = produceWithPatches(
state,
(draft) => {
const result = reducer(draft.present, action)
if (typeof result !== 'undefined') {
draft.present = result
}
},
)
let finalState = nextState
const undoable = action.meta?.undoable ?? true
if (undoable) {
finalState = createNextState(finalState, (draft) => {
draft.past.push({
undo: undoPatch,
redo: redoPatch,
})
draft.future = []
})
}
return finalState
}
},
{
withoutPayload() {
return (options?: UndoableOptions) => ({
payload: undefined,
meta: options,
})
},
withPayload<P>() {
return (
...[payload, options]: IfMaybeUndefined<
P,
[payload?: P, options?: UndoableOptions],
[payload: P, options?: UndoableOptions]
>
) => ({ payload: payload as P, meta: options })
},
},
),
}
const createAppSlice = buildCreateSlice({
creators: {
historyMethods: historyMethodsCreator,
undoable: undoableCreator,
},
})
test('history slice', () => {
const historySlice = createAppSlice({
name: 'history',
initialState: getInitialHistoryState({ value: 1 }),
reducers: (create) => ({
...create.historyMethods(),
increment: create.preparedReducer(
create.undoable.withoutPayload(),
create.undoable((state) => {
state.value++
}),
),
incrementBy: create.preparedReducer(
create.undoable.withPayload<number>(),
create.undoable((state, action) => {
state.value += action.payload
}),
),
}),
selectors: {
selectValue: (state) => state.present.value,
},
})
const {
actions: { increment, incrementBy, undo, redo, reset },
selectors: { selectValue },
} = historySlice
const store = configureStore({
reducer: { [historySlice.reducerPath]: historySlice.reducer },
})
expect(selectValue(store.getState())).toBe(1)
store.dispatch(increment())
expect(selectValue(store.getState())).toBe(2)
store.dispatch(undo())
expect(selectValue(store.getState())).toBe(1)
store.dispatch(incrementBy(3))
expect(selectValue(store.getState())).toBe(4)
store.dispatch(undo())
expect(selectValue(store.getState())).toBe(1)
store.dispatch(redo())
expect(selectValue(store.getState())).toBe(4)
store.dispatch(reset())
expect(selectValue(store.getState())).toBe(1)
})
})
describe('context methods throw errors if used incorrectly', () => {
const makeSliceWithHandler = (
handle: ReducerCreator<typeof loaderCreatorType>['handle'],
) => {
const loaderCreator: ReducerCreator<typeof loaderCreatorType> = {
type: loaderCreatorType,
create(reducers) {
return {
_reducerDefinitionType: loaderCreatorType,
...reducers,
}
},
handle,
}
const createAppSlice = buildCreateSlice({
creators: {
loader: loaderCreator,
},
})
return createAppSlice({
name: 'loader',
initialState: {} as Partial<Record<string, true>>,
reducers: (create) => ({
addLoader: create.loader({}),
}),
})
}
test('context.addCase throws if called twice for same type', () => {
expect(() =>
makeSliceWithHandler((_details, _def, context) => {
context.addCase('foo', () => {}).addCase('foo', () => {})
}),
).toThrowErrorMatchingInlineSnapshot(
`[Error: \`context.addCase\` cannot be called with two reducers for the same action type: foo]`,
)
})
test('context.addCase throws if empty action type', () => {
expect(() =>
makeSliceWithHandler((_details, _def, context) => {
context.addCase('', () => {})
}),