-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
createReducer.test.ts
616 lines (551 loc) · 18.1 KB
/
createReducer.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
import { vi } from 'vitest'
import type {
CaseReducer,
PayloadAction,
Draft,
Reducer,
AnyAction,
} from '@reduxjs/toolkit'
import { createReducer, createAction, createNextState } from '@reduxjs/toolkit'
import {
mockConsole,
createConsole,
getLog,
} from 'console-testing-library/pure'
interface Todo {
text: string
completed?: boolean
}
interface AddTodoPayload {
newTodo: Todo
}
interface ToggleTodoPayload {
index: number
}
type TodoState = Todo[]
type TodosReducer = Reducer<TodoState, PayloadAction<any>>
type AddTodoReducer = CaseReducer<
TodoState,
PayloadAction<AddTodoPayload, 'ADD_TODO'>
>
type ToggleTodoReducer = CaseReducer<
TodoState,
PayloadAction<ToggleTodoPayload, 'TOGGLE_TODO'>
>
type CreateReducer = typeof createReducer
describe('createReducer', () => {
let restore: () => void
beforeEach(() => {
restore = mockConsole(createConsole())
})
describe('given impure reducers with immer', () => {
const addTodo: AddTodoReducer = (state, action) => {
const { newTodo } = action.payload
// Can safely call state.push() here
state.push({ ...newTodo, completed: false })
}
const toggleTodo: ToggleTodoReducer = (state, action) => {
const { index } = action.payload
const todo = state[index]
// Can directly modify the todo object
todo.completed = !todo.completed
}
const todosReducer = createReducer([] as TodoState, (builder) => {
builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
})
behavesLikeReducer(todosReducer)
})
describe('Deprecation warnings', () => {
let originalNodeEnv = process.env.NODE_ENV
beforeEach(() => {
vi.resetModules()
})
afterEach(() => {
process.env.NODE_ENV = originalNodeEnv
})
it('Throws an error if the legacy object notation is used', async () => {
const { createReducer } = await import('../createReducer')
const wrapper = () => {
// @ts-ignore
let dummyReducer = (createReducer as CreateReducer)([] as TodoState, {})
}
expect(wrapper).toThrowError(
/The object notation for `createReducer` has been removed/
)
expect(wrapper).toThrowError(
/The object notation for `createReducer` has been removed/
)
})
it('Crashes in production', async () => {
process.env.NODE_ENV = 'production'
const { createReducer } = await import('../createReducer')
const wrapper = () => {
// @ts-ignore
let dummyReducer = (createReducer as CreateReducer)([] as TodoState, {})
}
expect(wrapper).toThrowError()
})
})
describe('Immer in a production environment', () => {
let originalNodeEnv = process.env.NODE_ENV
beforeEach(() => {
vi.resetModules()
process.env.NODE_ENV = 'production'
})
afterEach(() => {
process.env.NODE_ENV = originalNodeEnv
})
test('Freezes data in production', async () => {
const { createReducer } = await import('../createReducer')
const addTodo: AddTodoReducer = (state, action) => {
const { newTodo } = action.payload
state.push({ ...newTodo, completed: false })
}
const toggleTodo: ToggleTodoReducer = (state, action) => {
const { index } = action.payload
const todo = state[index]
todo.completed = !todo.completed
}
const todosReducer = createReducer([] as TodoState, (builder) => {
builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
})
const result = todosReducer([], {
type: 'ADD_TODO',
payload: { text: 'Buy milk' },
})
const mutateStateOutsideReducer = () => (result[0].text = 'edited')
expect(mutateStateOutsideReducer).toThrowError(
'Cannot add property text, object is not extensible'
)
})
test('Freezes initial state', () => {
const initialState = [{ text: 'Buy milk' }]
const todosReducer = createReducer(initialState, () => {})
const frozenInitialState = todosReducer(undefined, { type: 'dummy' })
const mutateStateOutsideReducer = () =>
(frozenInitialState[0].text = 'edited')
expect(mutateStateOutsideReducer).toThrowError(
/Cannot assign to read only property/
)
})
test('does not throw error if initial state is not draftable', () => {
expect(() =>
createReducer(new URLSearchParams(), () => {})
).not.toThrowError()
})
})
describe('given pure reducers with immutable updates', () => {
const addTodo: AddTodoReducer = (state, action) => {
const { newTodo } = action.payload
// Updates the state immutably without relying on immer
return state.concat({ ...newTodo, completed: false })
}
const toggleTodo: ToggleTodoReducer = (state, action) => {
const { index } = action.payload
// Updates the todo object immutably withot relying on immer
return state.map((todo, i) => {
if (i !== index) return todo
return { ...todo, completed: !todo.completed }
})
}
const todosReducer = createReducer([] as TodoState, (builder) => {
builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
})
behavesLikeReducer(todosReducer)
})
describe('Accepts a lazy state init function to generate initial state', () => {
const addTodo: AddTodoReducer = (state, action) => {
const { newTodo } = action.payload
state.push({ ...newTodo, completed: false })
}
const toggleTodo: ToggleTodoReducer = (state, action) => {
const { index } = action.payload
const todo = state[index]
todo.completed = !todo.completed
}
const lazyStateInit = () => [] as TodoState
const todosReducer = createReducer([] as TodoState, (builder) => {
builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
})
behavesLikeReducer(todosReducer)
it('Should only call the init function when `undefined` state is passed in', () => {
const spy = vi.fn().mockReturnValue(42)
const dummyReducer = createReducer(spy, () => {})
expect(spy).not.toHaveBeenCalled()
dummyReducer(123, { type: 'dummy' })
expect(spy).not.toHaveBeenCalled()
const initialState = dummyReducer(undefined, { type: 'dummy' })
expect(spy).toHaveBeenCalledTimes(1)
})
})
describe('given draft state from immer', () => {
const addTodo: AddTodoReducer = (state, action) => {
const { newTodo } = action.payload
// Can safely call state.push() here
state.push({ ...newTodo, completed: false })
}
const toggleTodo: ToggleTodoReducer = (state, action) => {
const { index } = action.payload
const todo = state[index]
// Can directly modify the todo object
todo.completed = !todo.completed
}
const todosReducer = createReducer([] as TodoState, (builder) => {
builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
})
const wrappedReducer: TodosReducer = (state = [], action) => {
return createNextState(state, (draft: Draft<TodoState>) => {
todosReducer(draft, action)
})
}
behavesLikeReducer(wrappedReducer)
})
describe('alternative builder callback for actionMap', () => {
const increment = createAction<number, 'increment'>('increment')
const decrement = createAction<number, 'decrement'>('decrement')
test('can be used with ActionCreators', () => {
const reducer = createReducer(0, (builder) =>
builder
.addCase(increment, (state, action) => state + action.payload)
.addCase(decrement, (state, action) => state - action.payload)
)
expect(reducer(0, increment(5))).toBe(5)
expect(reducer(5, decrement(5))).toBe(0)
})
test('can be used with string types', () => {
const reducer = createReducer(0, (builder) =>
builder
.addCase(
'increment',
(state, action: { type: 'increment'; payload: number }) =>
state + action.payload
)
.addCase(
'decrement',
(state, action: { type: 'decrement'; payload: number }) =>
state - action.payload
)
)
expect(reducer(0, increment(5))).toBe(5)
expect(reducer(5, decrement(5))).toBe(0)
})
test('can be used with ActionCreators and string types combined', () => {
const reducer = createReducer(0, (builder) =>
builder
.addCase(increment, (state, action) => state + action.payload)
.addCase(
'decrement',
(state, action: { type: 'decrement'; payload: number }) =>
state - action.payload
)
)
expect(reducer(0, increment(5))).toBe(5)
expect(reducer(5, decrement(5))).toBe(0)
})
test('will throw an error when returning undefined from a non-draftable state', () => {
const reducer = createReducer(0, (builder) =>
builder.addCase(
'decrement',
(state, action: { type: 'decrement'; payload: number }) => {}
)
)
expect(() => reducer(5, decrement(5))).toThrowErrorMatchingInlineSnapshot(
`"A case reducer on a non-draftable value must not return undefined"`
)
})
test('allows you to return undefined if the state was null, thus skipping an update', () => {
const reducer = createReducer(null as number | null, (builder) =>
builder.addCase(
'decrement',
(state, action: { type: 'decrement'; payload: number }) => {
if (typeof state === 'number') {
return state - action.payload
}
return undefined
}
)
)
expect(reducer(0, decrement(5))).toBe(-5)
expect(reducer(null, decrement(5))).toBe(null)
})
test('allows you to return null', () => {
const reducer = createReducer(0 as number | null, (builder) =>
builder.addCase(
'decrement',
(state, action: { type: 'decrement'; payload: number }) => {
return null
}
)
)
expect(reducer(5, decrement(5))).toBe(null)
})
test('allows you to return 0', () => {
const reducer = createReducer(0, (builder) =>
builder.addCase(
'decrement',
(state, action: { type: 'decrement'; payload: number }) =>
state - action.payload
)
)
expect(reducer(5, decrement(5))).toBe(0)
})
test('will throw if the same type is used twice', () => {
expect(() =>
createReducer(0, (builder) =>
builder
.addCase(increment, (state, action) => state + action.payload)
.addCase(increment, (state, action) => state + action.payload)
.addCase(decrement, (state, action) => state - action.payload)
)
).toThrowErrorMatchingInlineSnapshot(
`"addCase cannot be called with two reducers for the same action type"`
)
expect(() =>
createReducer(0, (builder) =>
builder
.addCase(increment, (state, action) => state + action.payload)
.addCase('increment', (state) => state + 1)
.addCase(decrement, (state, action) => state - action.payload)
)
).toThrowErrorMatchingInlineSnapshot(
`"addCase cannot be called with two reducers for the same action type"`
)
})
})
describe('builder "addMatcher" method', () => {
const prepareNumberAction = (payload: number) => ({
payload,
meta: { type: 'number_action' },
})
const prepareStringAction = (payload: string) => ({
payload,
meta: { type: 'string_action' },
})
const numberActionMatcher = (a: AnyAction): a is PayloadAction<number> =>
a.meta && a.meta.type === 'number_action'
const stringActionMatcher = (a: AnyAction): a is PayloadAction<string> =>
a.meta && a.meta.type === 'string_action'
const incrementBy = createAction('increment', prepareNumberAction)
const decrementBy = createAction('decrement', prepareNumberAction)
const concatWith = createAction('concat', prepareStringAction)
const initialState = { numberActions: 0, stringActions: 0 }
test('uses the reducer of matching actionMatchers', () => {
const reducer = createReducer(initialState, (builder) =>
builder
.addMatcher(numberActionMatcher, (state) => {
state.numberActions += 1
})
.addMatcher(stringActionMatcher, (state) => {
state.stringActions += 1
})
)
expect(reducer(undefined, incrementBy(1))).toEqual({
numberActions: 1,
stringActions: 0,
})
expect(reducer(undefined, decrementBy(1))).toEqual({
numberActions: 1,
stringActions: 0,
})
expect(reducer(undefined, concatWith('foo'))).toEqual({
numberActions: 0,
stringActions: 1,
})
})
test('falls back to defaultCase', () => {
const reducer = createReducer(initialState, (builder) =>
builder
.addCase(concatWith, (state) => {
state.stringActions += 1
})
.addMatcher(numberActionMatcher, (state) => {
state.numberActions += 1
})
.addDefaultCase((state) => {
state.numberActions = -1
state.stringActions = -1
})
)
expect(reducer(undefined, { type: 'somethingElse' })).toEqual({
numberActions: -1,
stringActions: -1,
})
})
test('runs reducer cases followed by all matching actionMatchers', () => {
const reducer = createReducer(initialState, (builder) =>
builder
.addCase(incrementBy, (state) => {
state.numberActions = state.numberActions * 10 + 1
})
.addMatcher(numberActionMatcher, (state) => {
state.numberActions = state.numberActions * 10 + 2
})
.addMatcher(stringActionMatcher, (state) => {
state.stringActions = state.stringActions * 10 + 1
})
.addMatcher(numberActionMatcher, (state) => {
state.numberActions = state.numberActions * 10 + 3
})
)
expect(reducer(undefined, incrementBy(1))).toEqual({
numberActions: 123,
stringActions: 0,
})
expect(reducer(undefined, decrementBy(1))).toEqual({
numberActions: 23,
stringActions: 0,
})
expect(reducer(undefined, concatWith('foo'))).toEqual({
numberActions: 0,
stringActions: 1,
})
})
test('works with `actionCreator.match`', () => {
const reducer = createReducer(initialState, (builder) =>
builder.addMatcher(incrementBy.match, (state) => {
state.numberActions += 100
})
)
expect(reducer(undefined, incrementBy(1))).toEqual({
numberActions: 100,
stringActions: 0,
})
})
test('calling addCase, addMatcher and addDefaultCase in a nonsensical order should result in an error in development mode', () => {
expect(() =>
createReducer(initialState, (builder: any) =>
builder
.addMatcher(numberActionMatcher, () => {})
.addCase(incrementBy, () => {})
)
).toThrowErrorMatchingInlineSnapshot(
`"\`builder.addCase\` should only be called before calling \`builder.addMatcher\`"`
)
expect(() =>
createReducer(initialState, (builder: any) =>
builder.addDefaultCase(() => {}).addCase(incrementBy, () => {})
)
).toThrowErrorMatchingInlineSnapshot(
`"\`builder.addCase\` should only be called before calling \`builder.addDefaultCase\`"`
)
expect(() =>
createReducer(initialState, (builder: any) =>
builder
.addDefaultCase(() => {})
.addMatcher(numberActionMatcher, () => {})
)
).toThrowErrorMatchingInlineSnapshot(
`"\`builder.addMatcher\` should only be called before calling \`builder.addDefaultCase\`"`
)
expect(() =>
createReducer(initialState, (builder: any) =>
builder.addDefaultCase(() => {}).addDefaultCase(() => {})
)
).toThrowErrorMatchingInlineSnapshot(
`"\`builder.addDefaultCase\` can only be called once"`
)
})
})
})
function behavesLikeReducer(todosReducer: TodosReducer) {
it('should handle initial state', () => {
const initialAction = { type: '', payload: undefined }
expect(todosReducer(undefined, initialAction)).toEqual([])
})
it('should handle ADD_TODO', () => {
expect(
todosReducer([], {
type: 'ADD_TODO',
payload: { newTodo: { text: 'Run the tests' } },
})
).toEqual([
{
text: 'Run the tests',
completed: false,
},
])
expect(
todosReducer(
[
{
text: 'Run the tests',
completed: false,
},
],
{
type: 'ADD_TODO',
payload: { newTodo: { text: 'Use Redux' } },
}
)
).toEqual([
{
text: 'Run the tests',
completed: false,
},
{
text: 'Use Redux',
completed: false,
},
])
expect(
todosReducer(
[
{
text: 'Run the tests',
completed: false,
},
{
text: 'Use Redux',
completed: false,
},
],
{
type: 'ADD_TODO',
payload: { newTodo: { text: 'Fix the tests' } },
}
)
).toEqual([
{
text: 'Run the tests',
completed: false,
},
{
text: 'Use Redux',
completed: false,
},
{
text: 'Fix the tests',
completed: false,
},
])
})
it('should handle TOGGLE_TODO', () => {
expect(
todosReducer(
[
{
text: 'Run the tests',
completed: false,
},
{
text: 'Use Redux',
completed: false,
},
],
{
type: 'TOGGLE_TODO',
payload: { index: 0 },
}
)
).toEqual([
{
text: 'Run the tests',
completed: true,
},
{
text: 'Use Redux',
completed: false,
},
])
})
}