Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/src/tests/createReducer.test.ts

raw
1 import type {
2 CaseReducer,
3 Draft,
4 PayloadAction,
5 Reducer,
6 UnknownAction,
7 } from '@reduxjs/toolkit'
8 import {
9 createAction,
10 createNextState,
11 createReducer,
12 isPlainObject,
13 } from '@reduxjs/toolkit'
14
15 interface Todo {
16 text: string
17 completed?: boolean
18 }
19
20 interface AddTodoPayload {
21 newTodo: Todo
22 }
23
24 interface ToggleTodoPayload {
25 index: number
26 }
27
28 type TodoState = Todo[]
29 type TodosReducer = Reducer<TodoState, PayloadAction<any>>
30 type AddTodoReducer = CaseReducer<
31 TodoState,
32 PayloadAction<AddTodoPayload, 'ADD_TODO'>
33 >
34
35 type ToggleTodoReducer = CaseReducer<
36 TodoState,
37 PayloadAction<ToggleTodoPayload, 'TOGGLE_TODO'>
38 >
39
40 type CreateReducer = typeof createReducer
41
42 describe('createReducer', () => {
43 describe('given impure reducers with immer', () => {
44 const addTodo: AddTodoReducer = (state, action) => {
45 const { newTodo } = action.payload
46
47 // Can safely call state.push() here
48 state.push({ ...newTodo, completed: false })
49 }
50
51 const toggleTodo: ToggleTodoReducer = (state, action) => {
52 const { index } = action.payload
53
54 const todo = state[index]
55 // Can directly modify the todo object
56 todo.completed = !todo.completed
57 }
58
59 const todosReducer = createReducer([] as TodoState, (builder) => {
60 builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
61 })
62
63 behavesLikeReducer(todosReducer)
64 })
65
66 describe('Deprecation warnings', () => {
67 beforeEach(() => {
68 vi.resetModules()
69 })
70
71 afterEach(() => {
72 vi.unstubAllEnvs()
73 })
74
75 it('Throws an error if the legacy object notation is used', async () => {
76 const { createReducer } = await import('../createReducer')
77 const wrapper = () => {
78 const dummyReducer = (createReducer as CreateReducer)(
79 [] as TodoState,
80 // @ts-ignore
81 {},
82 )
83 }
84
85 expect(wrapper).toThrowError(
86 /The object notation for `createReducer` has been removed/,
87 )
88
89 expect(wrapper).toThrowError(
90 /The object notation for `createReducer` has been removed/,
91 )
92 })
93
94 it('Crashes in production', async () => {
95 vi.stubEnv('NODE_ENV', 'production')
96 const { createReducer } = await import('../createReducer')
97 const wrapper = () => {
98 const dummyReducer = (createReducer as CreateReducer)(
99 [] as TodoState,
100 // @ts-ignore
101 {},
102 )
103 }
104
105 expect(wrapper).toThrowError()
106 })
107 })
108
109 describe('Immer in a production environment', () => {
110 beforeEach(() => {
111 vi.resetModules()
112 vi.stubEnv('NODE_ENV', 'production')
113 })
114
115 afterEach(() => {
116 vi.unstubAllEnvs()
117 })
118
119 test('Freezes data in production', async () => {
120 const { createReducer } = await import('../createReducer')
121 const addTodo: AddTodoReducer = (state, action) => {
122 const { newTodo } = action.payload
123 state.push({ ...newTodo, completed: false })
124 }
125
126 const toggleTodo: ToggleTodoReducer = (state, action) => {
127 const { index } = action.payload
128 const todo = state[index]
129 todo.completed = !todo.completed
130 }
131
132 const todosReducer = createReducer([] as TodoState, (builder) => {
133 builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
134 })
135
136 const result = todosReducer([], {
137 type: 'ADD_TODO',
138 payload: { text: 'Buy milk' },
139 })
140
141 const mutateStateOutsideReducer = () => (result[0].text = 'edited')
142 expect(mutateStateOutsideReducer).toThrowError(
143 'Cannot add property text, object is not extensible',
144 )
145 })
146
147 test('Freezes initial state', () => {
148 const initialState = [{ text: 'Buy milk' }]
149 const todosReducer = createReducer(initialState, () => {})
150 const frozenInitialState = todosReducer(undefined, { type: 'dummy' })
151
152 const mutateStateOutsideReducer = () =>
153 (frozenInitialState[0].text = 'edited')
154 expect(mutateStateOutsideReducer).toThrowError(
155 /Cannot assign to read only property/,
156 )
157 })
158 test('does not throw error if initial state is not draftable', () => {
159 expect(() =>
160 createReducer(new URLSearchParams(), () => {}),
161 ).not.toThrowError()
162 })
163 })
164
165 describe('given pure reducers with immutable updates', () => {
166 const addTodo: AddTodoReducer = (state, action) => {
167 const { newTodo } = action.payload
168
169 // Updates the state immutably without relying on immer
170 return state.concat({ ...newTodo, completed: false })
171 }
172
173 const toggleTodo: ToggleTodoReducer = (state, action) => {
174 const { index } = action.payload
175
176 // Updates the todo object immutably withot relying on immer
177 return state.map((todo, i) => {
178 if (i !== index) return todo
179 return { ...todo, completed: !todo.completed }
180 })
181 }
182
183 const todosReducer = createReducer([] as TodoState, (builder) => {
184 builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
185 })
186
187 behavesLikeReducer(todosReducer)
188 })
189
190 describe('Accepts a lazy state init function to generate initial state', () => {
191 const addTodo: AddTodoReducer = (state, action) => {
192 const { newTodo } = action.payload
193 state.push({ ...newTodo, completed: false })
194 }
195
196 const toggleTodo: ToggleTodoReducer = (state, action) => {
197 const { index } = action.payload
198 const todo = state[index]
199 todo.completed = !todo.completed
200 }
201
202 const lazyStateInit = () => [] as TodoState
203
204 const todosReducer = createReducer([] as TodoState, (builder) => {
205 builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
206 })
207
208 behavesLikeReducer(todosReducer)
209
210 it('Should only call the init function when `undefined` state is passed in', () => {
211 const spy = vi.fn().mockReturnValue(42)
212
213 const dummyReducer = createReducer(spy, () => {})
214 expect(spy).not.toHaveBeenCalled()
215
216 dummyReducer(123, { type: 'dummy' })
217 expect(spy).not.toHaveBeenCalled()
218
219 const initialState = dummyReducer(undefined, { type: 'dummy' })
220 expect(spy).toHaveBeenCalledOnce()
221 })
222 })
223
224 describe('given draft state from immer', () => {
225 const addTodo: AddTodoReducer = (state, action) => {
226 const { newTodo } = action.payload
227
228 // Can safely call state.push() here
229 state.push({ ...newTodo, completed: false })
230 }
231
232 const toggleTodo: ToggleTodoReducer = (state, action) => {
233 const { index } = action.payload
234
235 const todo = state[index]
236 // Can directly modify the todo object
237 todo.completed = !todo.completed
238 }
239
240 const todosReducer = createReducer([] as TodoState, (builder) => {
241 builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)
242 })
243
244 const wrappedReducer: TodosReducer = (state = [], action) => {
245 return createNextState(state, (draft: Draft<TodoState>) => {
246 todosReducer(draft, action)
247 })
248 }
249
250 behavesLikeReducer(wrappedReducer)
251 })
252
253 describe('builder callback for actionMap', () => {
254 const increment = createAction<number, 'increment'>('increment')
255 const decrement = createAction<number, 'decrement'>('decrement')
256
257 test('can be used with ActionCreators', () => {
258 const reducer = createReducer(0, (builder) =>
259 builder
260 .addCase(increment, (state, action) => state + action.payload)
261 .addCase(decrement, (state, action) => state - action.payload),
262 )
263 expect(reducer(0, increment(5))).toBe(5)
264 expect(reducer(5, decrement(5))).toBe(0)
265 })
266 test('can be used with string types', () => {
267 const reducer = createReducer(0, (builder) =>
268 builder
269 .addCase(
270 'increment',
271 (state, action: { type: 'increment'; payload: number }) =>
272 state + action.payload,
273 )
274 .addCase(
275 'decrement',
276 (state, action: { type: 'decrement'; payload: number }) =>
277 state - action.payload,
278 ),
279 )
280 expect(reducer(0, increment(5))).toBe(5)
281 expect(reducer(5, decrement(5))).toBe(0)
282 })
283 test('can be used with ActionCreators and string types combined', () => {
284 const reducer = createReducer(0, (builder) =>
285 builder
286 .addCase(increment, (state, action) => state + action.payload)
287 .addCase(
288 'decrement',
289 (state, action: { type: 'decrement'; payload: number }) =>
290 state - action.payload,
291 ),
292 )
293 expect(reducer(0, increment(5))).toBe(5)
294 expect(reducer(5, decrement(5))).toBe(0)
295 })
296 test('will throw an error when returning undefined from a non-draftable state', () => {
297 const reducer = createReducer(0, (builder) =>
298 builder.addCase(
299 'decrement',
300 (state, action: { type: 'decrement'; payload: number }) => {},
301 ),
302 )
303 expect(() => reducer(5, decrement(5))).toThrowErrorMatchingInlineSnapshot(
304 `[Error: A case reducer on a non-draftable value must not return undefined]`,
305 )
306 })
307 test('allows you to return undefined if the state was null, thus skipping an update', () => {
308 const reducer = createReducer(null as number | null, (builder) =>
309 builder.addCase(
310 'decrement',
311 (state, action: { type: 'decrement'; payload: number }) => {
312 if (typeof state === 'number') {
313 return state - action.payload
314 }
315 return undefined
316 },
317 ),
318 )
319 expect(reducer(0, decrement(5))).toBe(-5)
320 expect(reducer(null, decrement(5))).toBe(null)
321 })
322 test('allows you to return null', () => {
323 const reducer = createReducer(0 as number | null, (builder) =>
324 builder.addCase(
325 'decrement',
326 (state, action: { type: 'decrement'; payload: number }) => {
327 return null
328 },
329 ),
330 )
331 expect(reducer(5, decrement(5))).toBe(null)
332 })
333 test('allows you to return 0', () => {
334 const reducer = createReducer(0, (builder) =>
335 builder.addCase(
336 'decrement',
337 (state, action: { type: 'decrement'; payload: number }) =>
338 state - action.payload,
339 ),
340 )
341 expect(reducer(5, decrement(5))).toBe(0)
342 })
343 test('will throw if the same type is used twice', () => {
344 expect(() =>
345 createReducer(0, (builder) =>
346 builder
347 .addCase(increment, (state, action) => state + action.payload)
348 .addCase(increment, (state, action) => state + action.payload)
349 .addCase(decrement, (state, action) => state - action.payload),
350 ),
351 ).toThrowErrorMatchingInlineSnapshot(
352 `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
353 )
354 expect(() =>
355 createReducer(0, (builder) =>
356 builder
357 .addCase(increment, (state, action) => state + action.payload)
358 .addCase('increment', (state) => state + 1)
359 .addCase(decrement, (state, action) => state - action.payload),
360 ),
361 ).toThrowErrorMatchingInlineSnapshot(
362 `[Error: \`builder.addCase\` cannot be called with two reducers for the same action type 'increment']`,
363 )
364 })
365
366 test('will throw if an empty type is used', () => {
367 const customActionCreator = (payload: number) => ({
368 type: 'custom_action',
369 payload,
370 })
371 customActionCreator.type = ''
372 expect(() =>
373 createReducer(0, (builder) =>
374 builder.addCase(
375 customActionCreator,
376 (state, action) => state + action.payload,
377 ),
378 ),
379 ).toThrowErrorMatchingInlineSnapshot(
380 `[Error: \`builder.addCase\` cannot be called with an empty action type]`,
381 )
382 })
383 })
384
385 describe('builder "addMatcher" method', () => {
386 const prepareNumberAction = (payload: number) => ({
387 payload,
388 meta: { type: 'number_action' },
389 })
390 const prepareStringAction = (payload: string) => ({
391 payload,
392 meta: { type: 'string_action' },
393 })
394
395 const numberActionMatcher = (
396 a: UnknownAction,
397 ): a is PayloadAction<number> =>
398 isPlainObject(a.meta) &&
399 'type' in a.meta &&
400 (a.meta as Record<'type', unknown>).type === 'number_action'
401
402 const stringActionMatcher = (
403 a: UnknownAction,
404 ): a is PayloadAction<string> =>
405 isPlainObject(a.meta) &&
406 'type' in a.meta &&
407 (a.meta as Record<'type', unknown>).type === 'string_action'
408
409 const incrementBy = createAction('increment', prepareNumberAction)
410 const decrementBy = createAction('decrement', prepareNumberAction)
411 const concatWith = createAction('concat', prepareStringAction)
412
413 const initialState = { numberActions: 0, stringActions: 0 }
414
415 test('uses the reducer of matching actionMatchers', () => {
416 const reducer = createReducer(initialState, (builder) =>
417 builder
418 .addMatcher(numberActionMatcher, (state) => {
419 state.numberActions += 1
420 })
421 .addMatcher(stringActionMatcher, (state) => {
422 state.stringActions += 1
423 }),
424 )
425 expect(reducer(undefined, incrementBy(1))).toEqual({
426 numberActions: 1,
427 stringActions: 0,
428 })
429 expect(reducer(undefined, decrementBy(1))).toEqual({
430 numberActions: 1,
431 stringActions: 0,
432 })
433 expect(reducer(undefined, concatWith('foo'))).toEqual({
434 numberActions: 0,
435 stringActions: 1,
436 })
437 })
438 test('falls back to defaultCase', () => {
439 const reducer = createReducer(initialState, (builder) =>
440 builder
441 .addCase(concatWith, (state) => {
442 state.stringActions += 1
443 })
444 .addMatcher(numberActionMatcher, (state) => {
445 state.numberActions += 1
446 })
447 .addDefaultCase((state) => {
448 state.numberActions = -1
449 state.stringActions = -1
450 }),
451 )
452 expect(reducer(undefined, { type: 'somethingElse' })).toEqual({
453 numberActions: -1,
454 stringActions: -1,
455 })
456 })
457 test('runs reducer cases followed by all matching actionMatchers', () => {
458 const reducer = createReducer(initialState, (builder) =>
459 builder
460 .addCase(incrementBy, (state) => {
461 state.numberActions = state.numberActions * 10 + 1
462 })
463 .addMatcher(numberActionMatcher, (state) => {
464 state.numberActions = state.numberActions * 10 + 2
465 })
466 .addMatcher(stringActionMatcher, (state) => {
467 state.stringActions = state.stringActions * 10 + 1
468 })
469 .addMatcher(numberActionMatcher, (state) => {
470 state.numberActions = state.numberActions * 10 + 3
471 }),
472 )
473 expect(reducer(undefined, incrementBy(1))).toEqual({
474 numberActions: 123,
475 stringActions: 0,
476 })
477 expect(reducer(undefined, decrementBy(1))).toEqual({
478 numberActions: 23,
479 stringActions: 0,
480 })
481 expect(reducer(undefined, concatWith('foo'))).toEqual({
482 numberActions: 0,
483 stringActions: 1,
484 })
485 })
486 test('works with `actionCreator.match`', () => {
487 const reducer = createReducer(initialState, (builder) =>
488 builder.addMatcher(incrementBy.match, (state) => {
489 state.numberActions += 100
490 }),
491 )
492 expect(reducer(undefined, incrementBy(1))).toEqual({
493 numberActions: 100,
494 stringActions: 0,
495 })
496 })
497 test('calling addCase, addMatcher and addDefaultCase in a nonsensical order should result in an error in development mode', () => {
498 expect(() =>
499 createReducer(initialState, (builder: any) =>
500 builder
501 .addMatcher(numberActionMatcher, () => {})
502 .addCase(incrementBy, () => {}),
503 ),
504 ).toThrowErrorMatchingInlineSnapshot(
505 `[Error: \`builder.addCase\` should only be called before calling \`builder.addMatcher\`]`,
506 )
507 expect(() =>
508 createReducer(initialState, (builder: any) =>
509 builder.addDefaultCase(() => {}).addCase(incrementBy, () => {}),
510 ),
511 ).toThrowErrorMatchingInlineSnapshot(
512 `[Error: \`builder.addCase\` should only be called before calling \`builder.addDefaultCase\`]`,
513 )
514 expect(() =>
515 createReducer(initialState, (builder: any) =>
516 builder
517 .addDefaultCase(() => {})
518 .addMatcher(numberActionMatcher, () => {}),
519 ),
520 ).toThrowErrorMatchingInlineSnapshot(
521 `[Error: \`builder.addMatcher\` should only be called before calling \`builder.addDefaultCase\`]`,
522 )
523 expect(() =>
524 createReducer(initialState, (builder: any) =>
525 builder.addDefaultCase(() => {}).addDefaultCase(() => {}),
526 ),
527 ).toThrowErrorMatchingInlineSnapshot(
528 `[Error: \`builder.addDefaultCase\` can only be called once]`,
529 )
530 })
531 })
532 })
533
534 function behavesLikeReducer(todosReducer: TodosReducer) {
535 it('should handle initial state', () => {
536 const initialAction = { type: '', payload: undefined }
537 expect(todosReducer(undefined, initialAction)).toEqual([])
538 })
539
540 it('should handle ADD_TODO', () => {
541 expect(
542 todosReducer([], {
543 type: 'ADD_TODO',
544 payload: { newTodo: { text: 'Run the tests' } },
545 }),
546 ).toEqual([
547 {
548 text: 'Run the tests',
549 completed: false,
550 },
551 ])
552
553 expect(
554 todosReducer(
555 [
556 {
557 text: 'Run the tests',
558 completed: false,
559 },
560 ],
561 {
562 type: 'ADD_TODO',
563 payload: { newTodo: { text: 'Use Redux' } },
564 },
565 ),
566 ).toEqual([
567 {
568 text: 'Run the tests',
569 completed: false,
570 },
571 {
572 text: 'Use Redux',
573 completed: false,
574 },
575 ])
576
577 expect(
578 todosReducer(
579 [
580 {
581 text: 'Run the tests',
582 completed: false,
583 },
584 {
585 text: 'Use Redux',
586 completed: false,
587 },
588 ],
589 {
590 type: 'ADD_TODO',
591 payload: { newTodo: { text: 'Fix the tests' } },
592 },
593 ),
594 ).toEqual([
595 {
596 text: 'Run the tests',
597 completed: false,
598 },
599 {
600 text: 'Use Redux',
601 completed: false,
602 },
603 {
604 text: 'Fix the tests',
605 completed: false,
606 },
607 ])
608 })
609
610 it('should handle TOGGLE_TODO', () => {
611 expect(
612 todosReducer(
613 [
614 {
615 text: 'Run the tests',
616 completed: false,
617 },
618 {
619 text: 'Use Redux',
620 completed: false,
621 },
622 ],
623 {
624 type: 'TOGGLE_TODO',
625 payload: { index: 0 },
626 },
627 ),
628 ).toEqual([
629 {
630 text: 'Run the tests',
631 completed: true,
632 },
633 {
634 text: 'Use Redux',
635 completed: false,
636 },
637 ])
638 })
639 }