Spaces:
Running
Running
File size: 21,652 Bytes
c2b7eb3 | 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 | import type {
Action,
ConfigureStoreOptions,
Dispatch,
Middleware,
PayloadAction,
Reducer,
Store,
StoreEnhancer,
ThunkAction,
ThunkDispatch,
ThunkMiddleware,
UnknownAction,
} from '@reduxjs/toolkit'
import {
Tuple,
applyMiddleware,
combineReducers,
configureStore,
createSlice,
} from '@reduxjs/toolkit'
import { thunk } from 'redux-thunk'
const _anyMiddleware: any = () => () => () => {}
describe('type tests', () => {
test('configureStore() requires a valid reducer or reducer map.', () => {
configureStore({
reducer: (state, action) => 0,
})
configureStore({
reducer: {
counter1: () => 0,
counter2: () => 1,
},
})
// @ts-expect-error
configureStore({ reducer: 'not a reducer' })
// @ts-expect-error
configureStore({ reducer: { a: 'not a reducer' } })
// @ts-expect-error
configureStore({})
})
test('configureStore() infers the store state type.', () => {
const reducer: Reducer<number> = () => 0
const store = configureStore({ reducer })
expectTypeOf(store).toMatchTypeOf<Store<number, UnknownAction>>()
expectTypeOf(store).not.toMatchTypeOf<Store<string, UnknownAction>>()
})
test('configureStore() infers the store action type.', () => {
const reducer: Reducer<number, PayloadAction<number>> = () => 0
const store = configureStore({ reducer })
expectTypeOf(store).toMatchTypeOf<Store<number, PayloadAction<number>>>()
expectTypeOf(store).not.toMatchTypeOf<
Store<number, PayloadAction<string>>
>()
})
test('configureStore() accepts Tuple for middleware, but not plain array.', () => {
const middleware: Middleware = (store) => (next) => next
configureStore({
reducer: () => 0,
middleware: () => new Tuple(middleware),
})
configureStore({
reducer: () => 0,
// @ts-expect-error
middleware: () => [middleware],
})
configureStore({
reducer: () => 0,
// @ts-expect-error
middleware: () => new Tuple('not middleware'),
})
})
test('configureStore() accepts devTools flag.', () => {
configureStore({
reducer: () => 0,
devTools: true,
})
configureStore({
reducer: () => 0,
// @ts-expect-error
devTools: 'true',
})
})
test('configureStore() accepts devTools EnhancerOptions.', () => {
configureStore({
reducer: () => 0,
devTools: { name: 'myApp' },
})
configureStore({
reducer: () => 0,
// @ts-expect-error
devTools: { appName: 'myApp' },
})
})
test('configureStore() accepts preloadedState.', () => {
configureStore({
reducer: () => 0,
preloadedState: 0,
})
configureStore({
// @ts-expect-error
reducer: (_: number) => 0,
preloadedState: 'non-matching state type',
})
})
test('nullable state is preserved', () => {
const store = configureStore({
reducer: (): string | null => null,
})
expectTypeOf(store.getState()).toEqualTypeOf<string | null>()
})
test('configureStore() accepts store Tuple for enhancers, but not plain array', () => {
const enhancer = applyMiddleware(() => (next) => next)
const store = configureStore({
reducer: () => 0,
enhancers: () => new Tuple(enhancer),
})
const store2 = configureStore({
reducer: () => 0,
// @ts-expect-error
enhancers: () => [enhancer],
})
expectTypeOf(store.dispatch).toMatchTypeOf<
Dispatch & ThunkDispatch<number, undefined, UnknownAction>
>()
configureStore({
reducer: () => 0,
// @ts-expect-error
enhancers: () => new Tuple('not a store enhancer'),
})
const somePropertyStoreEnhancer: StoreEnhancer<{
someProperty: string
}> = (next) => {
return (reducer, preloadedState) => {
return {
...next(reducer, preloadedState),
someProperty: 'some value',
}
}
}
const anotherPropertyStoreEnhancer: StoreEnhancer<{
anotherProperty: number
}> = (next) => {
return (reducer, preloadedState) => {
return {
...next(reducer, preloadedState),
anotherProperty: 123,
}
}
}
const store3 = configureStore({
reducer: () => 0,
enhancers: () =>
new Tuple(somePropertyStoreEnhancer, anotherPropertyStoreEnhancer),
})
expectTypeOf(store3.dispatch).toEqualTypeOf<Dispatch>()
expectTypeOf(store3.someProperty).toBeString()
expectTypeOf(store3.anotherProperty).toBeNumber()
const storeWithCallback = configureStore({
reducer: () => 0,
enhancers: (getDefaultEnhancers) =>
getDefaultEnhancers()
.prepend(anotherPropertyStoreEnhancer)
.concat(somePropertyStoreEnhancer),
})
expectTypeOf(store3.dispatch).toMatchTypeOf<
Dispatch & ThunkDispatch<number, undefined, UnknownAction>
>()
expectTypeOf(store3.someProperty).toBeString()
expectTypeOf(store3.anotherProperty).toBeNumber()
const someStateExtendingEnhancer: StoreEnhancer<
{},
{ someProperty: string }
> =
(next) =>
(...args) => {
const store = next(...args)
const getState = () => ({
...store.getState(),
someProperty: 'some value',
})
return {
...store,
getState,
} as any
}
const anotherStateExtendingEnhancer: StoreEnhancer<
{},
{ anotherProperty: number }
> =
(next) =>
(...args) => {
const store = next(...args)
const getState = () => ({
...store.getState(),
anotherProperty: 123,
})
return {
...store,
getState,
} as any
}
const store4 = configureStore({
reducer: () => ({ aProperty: 0 }),
enhancers: () =>
new Tuple(someStateExtendingEnhancer, anotherStateExtendingEnhancer),
})
const state = store4.getState()
expectTypeOf(state.aProperty).toBeNumber()
expectTypeOf(state.someProperty).toBeString()
expectTypeOf(state.anotherProperty).toBeNumber()
const storeWithCallback2 = configureStore({
reducer: () => ({ aProperty: 0 }),
enhancers: (gDE) =>
gDE().concat(someStateExtendingEnhancer, anotherStateExtendingEnhancer),
})
const stateWithCallback = storeWithCallback2.getState()
expectTypeOf(stateWithCallback.aProperty).toBeNumber()
expectTypeOf(stateWithCallback.someProperty).toBeString()
expectTypeOf(stateWithCallback.anotherProperty).toBeNumber()
})
test('Preloaded state typings', () => {
const counterReducer1: Reducer<number> = () => 0
const counterReducer2: Reducer<number> = () => 0
test('partial preloaded state', () => {
const store = configureStore({
reducer: {
counter1: counterReducer1,
counter2: counterReducer2,
},
preloadedState: {
counter1: 0,
},
})
expectTypeOf(store.getState().counter1).toBeNumber()
expectTypeOf(store.getState().counter2).toBeNumber()
})
test('empty preloaded state', () => {
const store = configureStore({
reducer: {
counter1: counterReducer1,
counter2: counterReducer2,
},
preloadedState: {},
})
expectTypeOf(store.getState().counter1).toBeNumber()
expectTypeOf(store.getState().counter2).toBeNumber()
})
test('excess properties in preloaded state', () => {
const store = configureStore({
reducer: {
// @ts-expect-error
counter1: counterReducer1,
counter2: counterReducer2,
},
preloadedState: {
counter1: 0,
counter3: 5,
},
})
expectTypeOf(store.getState().counter1).toBeNumber()
expectTypeOf(store.getState().counter2).toBeNumber()
})
test('mismatching properties in preloaded state', () => {
const store = configureStore({
reducer: {
// @ts-expect-error
counter1: counterReducer1,
counter2: counterReducer2,
},
preloadedState: {
counter3: 5,
},
})
expectTypeOf(store.getState().counter1).toBeNumber()
expectTypeOf(store.getState().counter2).toBeNumber()
})
test('string preloaded state when expecting object', () => {
const store = configureStore({
reducer: {
// @ts-expect-error
counter1: counterReducer1,
counter2: counterReducer2,
},
preloadedState: 'test',
})
expectTypeOf(store.getState().counter1).toBeNumber()
expectTypeOf(store.getState().counter2).toBeNumber()
})
test('nested combineReducers allows partial', () => {
const store = configureStore({
reducer: {
group1: combineReducers({
counter1: counterReducer1,
counter2: counterReducer2,
}),
group2: combineReducers({
counter1: counterReducer1,
counter2: counterReducer2,
}),
},
preloadedState: {
group1: {
counter1: 5,
},
},
})
expectTypeOf(store.getState().group1.counter1).toBeNumber()
expectTypeOf(store.getState().group1.counter2).toBeNumber()
expectTypeOf(store.getState().group2.counter1).toBeNumber()
expectTypeOf(store.getState().group2.counter2).toBeNumber()
})
test('non-nested combineReducers does not allow partial', () => {
interface GroupState {
counter1: number
counter2: number
}
const initialState = { counter1: 0, counter2: 0 }
const group1Reducer: Reducer<GroupState> = (state = initialState) => state
const group2Reducer: Reducer<GroupState> = (state = initialState) => state
const store = configureStore({
reducer: {
// @ts-expect-error
group1: group1Reducer,
group2: group2Reducer,
},
preloadedState: {
group1: {
counter1: 5,
},
},
})
expectTypeOf(store.getState().group1.counter1).toBeNumber()
expectTypeOf(store.getState().group1.counter2).toBeNumber()
expectTypeOf(store.getState().group2.counter1).toBeNumber()
expectTypeOf(store.getState().group2.counter2).toBeNumber()
})
})
test('Dispatch typings', () => {
type StateA = number
const reducerA = () => 0
const thunkA = () => {
return (() => {}) as any as ThunkAction<Promise<'A'>, StateA, any, any>
}
type StateB = string
const thunkB = () => {
return (dispatch: Dispatch, getState: () => StateB) => {}
}
test('by default, dispatching Thunks is possible', () => {
const store = configureStore({
reducer: reducerA,
})
store.dispatch(thunkA())
// @ts-expect-error
store.dispatch(thunkB())
const res = store.dispatch((dispatch, getState) => {
return 42
})
const action = store.dispatch({ type: 'foo' })
})
test('return type of thunks and actions is inferred correctly', () => {
const slice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const store = configureStore({
reducer: {
counter: slice.reducer,
},
})
const action = slice.actions.incrementByAmount(2)
const dispatchResult = store.dispatch(action)
expectTypeOf(dispatchResult).toMatchTypeOf<{
type: string
payload: number
}>()
const promiseResult = store.dispatch(async (dispatch) => {
return 42
})
expectTypeOf(promiseResult).toEqualTypeOf<Promise<number>>()
const store2 = configureStore({
reducer: {
counter: slice.reducer,
},
middleware: (gDM) =>
gDM({
thunk: {
extraArgument: 42,
},
}),
})
const dispatchResult2 = store2.dispatch(action)
expectTypeOf(dispatchResult2).toMatchTypeOf<{
type: string
payload: number
}>()
})
test('removing the Thunk Middleware', () => {
const store = configureStore({
reducer: reducerA,
middleware: () => new Tuple(),
})
expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkA())
expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
})
test('adding the thunk middleware by hand', () => {
const store = configureStore({
reducer: reducerA,
middleware: () => new Tuple(thunk as ThunkMiddleware<StateA>),
})
store.dispatch(thunkA())
// @ts-expect-error
store.dispatch(thunkB())
})
test('custom middleware', () => {
const store = configureStore({
reducer: reducerA,
middleware: () =>
new Tuple(0 as unknown as Middleware<(a: StateA) => boolean, StateA>),
})
expectTypeOf(store.dispatch(5)).toBeBoolean()
expectTypeOf(store.dispatch(5)).not.toBeString()
})
test('multiple custom middleware', () => {
const middleware = [] as any as Tuple<
[
Middleware<(a: 'a') => 'A', StateA>,
Middleware<(b: 'b') => 'B', StateA>,
ThunkMiddleware<StateA>,
]
>
const store = configureStore({
reducer: reducerA,
middleware: () => middleware,
})
expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
expectTypeOf(store.dispatch('b')).toEqualTypeOf<'B'>()
expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
})
test('Accepts thunk with `unknown`, `undefined` or `null` ThunkAction extraArgument per default', () => {
const store = configureStore({ reducer: {} })
// undefined is the default value for the ThunkMiddleware extraArgument
store.dispatch(function () {} as ThunkAction<
void,
{},
undefined,
UnknownAction
>)
// `null` for the `extra` generic was previously documented in the RTK "Advanced Tutorial", but
// is a bad pattern and users should use `unknown` instead
// @ts-expect-error
store.dispatch(function () {} as ThunkAction<
void,
{},
null,
UnknownAction
>)
// unknown is the best way to type a ThunkAction if you do not care
// about the value of the extraArgument, as it will always work with every
// ThunkMiddleware, no matter the actual extraArgument type
store.dispatch(function () {} as ThunkAction<
void,
{},
unknown,
UnknownAction
>)
// @ts-expect-error
store.dispatch(function () {} as ThunkAction<
void,
{},
boolean,
UnknownAction
>)
})
test('custom middleware and getDefaultMiddleware', () => {
const store = configureStore({
reducer: reducerA,
middleware: (gDM) =>
gDM().prepend((() => {}) as any as Middleware<
(a: 'a') => 'A',
StateA
>),
})
expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
})
test('custom middleware and getDefaultMiddleware, using prepend', () => {
const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
_anyMiddleware
const store = configureStore({
reducer: reducerA,
middleware: (gDM) => {
const concatenated = gDM().prepend(otherMiddleware)
expectTypeOf(concatenated).toMatchTypeOf<
ReadonlyArray<
typeof otherMiddleware | ThunkMiddleware | Middleware<{}>
>
>()
return concatenated
},
})
expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
})
test('custom middleware and getDefaultMiddleware, using concat', () => {
const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
_anyMiddleware
const store = configureStore({
reducer: reducerA,
middleware: (gDM) => {
const concatenated = gDM().concat(otherMiddleware)
expectTypeOf(concatenated).toMatchTypeOf<
ReadonlyArray<
typeof otherMiddleware | ThunkMiddleware | Middleware<{}>
>
>()
return concatenated
},
})
expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
})
test('middlewareBuilder notation, getDefaultMiddleware (unconfigured)', () => {
const store = configureStore({
reducer: reducerA,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend((() => {}) as any as Middleware<
(a: 'a') => 'A',
StateA
>),
})
expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
})
test('middlewareBuilder notation, getDefaultMiddleware, concat & prepend', () => {
const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =
_anyMiddleware
const otherMiddleware2: Middleware<(a: 'b') => 'B', StateA> =
_anyMiddleware
const store = configureStore({
reducer: reducerA,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware()
.concat(otherMiddleware)
.prepend(otherMiddleware2),
})
expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()
expectTypeOf(store.dispatch('b')).toEqualTypeOf<'B'>()
expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkB())
})
test('middlewareBuilder notation, getDefaultMiddleware (thunk: false)', () => {
const store = configureStore({
reducer: reducerA,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({ thunk: false }).prepend(
(() => {}) as any as Middleware<(a: 'a') => 'A', StateA>,
),
})
expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()
expectTypeOf(store.dispatch).parameter(0).not.toMatchTypeOf(thunkA())
})
test("badly typed middleware won't make `dispatch` `any`", () => {
const store = configureStore({
reducer: reducerA,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(_anyMiddleware as Middleware<any>),
})
expectTypeOf(store.dispatch).not.toBeAny()
})
test("decorated `configureStore` won't make `dispatch` `never`", () => {
const someSlice = createSlice({
name: 'something',
initialState: null as any,
reducers: {
set(state) {
return state
},
},
})
function configureMyStore<S>(
options: Omit<ConfigureStoreOptions<S>, 'reducer'>,
) {
return configureStore({
...options,
reducer: someSlice.reducer,
})
}
const store = configureMyStore({})
expectTypeOf(store.dispatch).toBeFunction()
})
interface CounterState {
value: number
}
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
type Unsubscribe = () => void
// A fake middleware that tells TS that an unsubscribe callback is being returned for a given action
// This is the same signature that the "listener" middleware uses
const dummyMiddleware: Middleware<
{
(action: Action<'actionListenerMiddleware/add'>): Unsubscribe
},
CounterState
> = (storeApi) => (next) => (action) => {}
const store = configureStore({
reducer: counterSlice.reducer,
middleware: (gDM) => gDM().prepend(dummyMiddleware),
})
// Order matters here! We need the listener type to come first, otherwise
// the thunk middleware type kicks in and TS thinks a plain action is being returned
expectTypeOf(store.dispatch).toEqualTypeOf<
((action: Action<'actionListenerMiddleware/add'>) => Unsubscribe) &
ThunkDispatch<CounterState, undefined, UnknownAction> &
Dispatch<UnknownAction>
>()
const unsubscribe = store.dispatch({
type: 'actionListenerMiddleware/add',
} as const)
expectTypeOf(unsubscribe).toEqualTypeOf<Unsubscribe>()
})
})
|