Spaces:
Sleeping
Sleeping
File size: 28,623 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 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 | import { noop } from '@internal/listenerMiddleware/utils'
import type { PayloadAction, WithSlice } from '@reduxjs/toolkit'
import {
asyncThunkCreator,
buildCreateSlice,
combineSlices,
configureStore,
createAction,
createAsyncThunk,
createSlice,
} from '@reduxjs/toolkit'
type CreateSlice = typeof createSlice
describe('createSlice', () => {
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
beforeEach(() => {
vi.clearAllMocks()
})
afterAll(() => {
vi.restoreAllMocks()
})
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')
})
afterEach(() => {
vi.unstubAllEnvs()
})
it('should throw an error', () => {
createSlice({
name: 'test',
reducers: {},
initialState: undefined,
})
expect(consoleErrorSpy).toHaveBeenCalledOnce()
expect(consoleErrorSpy).toHaveBeenLastCalledWith(
'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 addAsyncThunk and async thunks', () => {
const asyncThunk = createAsyncThunk('test', (n: number) => n)
const slice = createSlice({
name: 'counter',
initialState: {
loading: false,
errored: false,
value: 0,
},
reducers: {},
extraReducers: (builder) =>
builder.addAsyncThunk(asyncThunk, {
pending(state) {
state.loading = true
},
fulfilled(state, action) {
state.value = action.payload
},
rejected(state) {
state.errored = true
},
settled(state) {
state.loading = false
},
}),
})
expect(
slice.reducer(undefined, asyncThunk.pending('requestId', 5)),
).toEqual({
loading: true,
errored: false,
value: 0,
})
expect(
slice.reducer(undefined, asyncThunk.fulfilled(5, 'requestId', 5)),
).toEqual({
loading: false,
errored: false,
value: 5,
})
expect(
slice.reducer(
undefined,
asyncThunk.rejected(new Error(), 'requestId', 5),
),
).toEqual({
loading: false,
errored: true,
value: 0,
})
})
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', () => {
beforeEach(() => {
vi.resetModules()
})
afterEach(() => {
vi.unstubAllEnvs()
})
// 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)
})
it('caches initial states for selectors', () => {
const slice = createSlice({
name: 'counter',
initialState: () => ({ value: 0 }),
reducers: {},
selectors: {
selectObj: (state) => state,
},
})
// not cached
expect(slice.getInitialState()).not.toBe(slice.getInitialState())
expect(slice.reducer(undefined, { type: 'dummy' })).not.toBe(
slice.reducer(undefined, { type: 'dummy' }),
)
const combinedReducer = combineSlices({
static: slice.reducer,
}).withLazyLoadedSlices<WithSlice<typeof slice>>()
const injected = slice.injectInto(combinedReducer)
// still not cached
expect(injected.getInitialState()).not.toBe(injected.getInitialState())
expect(injected.reducer(undefined, { type: 'dummy' })).not.toBe(
injected.reducer(undefined, { type: 'dummy' }),
)
// cached
expect(injected.selectSlice({})).toBe(injected.selectSlice({}))
expect(injected.selectors.selectObj({})).toBe(
injected.selectors.selectObj({}),
)
})
})
describe('reducers definition with asyncThunks', () => {
it('is disabled by default', () => {
expect(() =>
createSlice({
name: 'test',
initialState: [] as any[],
reducers: (create) => ({ thunk: create.asyncThunk(() => {}) }),
}),
).toThrowErrorMatchingInlineSnapshot(
`[Error: Cannot use \`create.asyncThunk\` in the built-in \`createSlice\`. Use \`buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })\` to create a customised version of \`createSlice\`.]`,
)
})
const createAppSlice = buildCreateSlice({
creators: { asyncThunk: asyncThunkCreator },
})
function pending(state: any[], action: any) {
state.push(['pendingReducer', action])
}
function fulfilled(state: any[], action: any) {
state.push(['fulfilledReducer', action])
}
function rejected(state: any[], action: any) {
state.push(['rejectedReducer', action])
}
function settled(state: any[], action: any) {
state.push(['settledReducer', action])
}
test('successful thunk', async () => {
const slice = createAppSlice({
name: 'test',
initialState: [] as any[],
reducers: (create) => ({
thunkReducers: create.asyncThunk(
function payloadCreator(arg: string, api) {
return Promise.resolve('resolved payload')
},
{ pending, fulfilled, rejected, settled },
),
}),
})
const store = configureStore({
reducer: slice.reducer,
})
await store.dispatch(slice.actions.thunkReducers('test'))
expect(store.getState()).toMatchObject([
[
'pendingReducer',
{
type: 'test/thunkReducers/pending',
payload: undefined,
},
],
[
'fulfilledReducer',
{
type: 'test/thunkReducers/fulfilled',
payload: 'resolved payload',
},
],
[
'settledReducer',
{
type: 'test/thunkReducers/fulfilled',
payload: 'resolved payload',
},
],
])
})
test('rejected thunk', async () => {
const slice = createAppSlice({
name: 'test',
initialState: [] as any[],
reducers: (create) => ({
thunkReducers: create.asyncThunk(
// payloadCreator isn't allowed to return never
function payloadCreator(arg: string, api): any {
throw new Error('')
},
{ pending, fulfilled, rejected, settled },
),
}),
})
const store = configureStore({
reducer: slice.reducer,
})
await store.dispatch(slice.actions.thunkReducers('test'))
expect(store.getState()).toMatchObject([
[
'pendingReducer',
{
type: 'test/thunkReducers/pending',
payload: undefined,
},
],
[
'rejectedReducer',
{
type: 'test/thunkReducers/rejected',
payload: undefined,
},
],
[
'settledReducer',
{
type: 'test/thunkReducers/rejected',
payload: undefined,
},
],
])
})
test('with options', async () => {
const slice = createAppSlice({
name: 'test',
initialState: [] as any[],
reducers: (create) => ({
thunkReducers: create.asyncThunk(
function payloadCreator(arg: string, api) {
return 'should not call this'
},
{
options: {
condition() {
return false
},
dispatchConditionRejection: true,
},
pending,
fulfilled,
rejected,
settled,
},
),
}),
})
const store = configureStore({
reducer: slice.reducer,
})
await store.dispatch(slice.actions.thunkReducers('test'))
expect(store.getState()).toMatchObject([
[
'rejectedReducer',
{
type: 'test/thunkReducers/rejected',
payload: undefined,
meta: { condition: true },
},
],
[
'settledReducer',
{
type: 'test/thunkReducers/rejected',
payload: undefined,
meta: { condition: true },
},
],
])
})
test('has caseReducers for the asyncThunk', async () => {
const slice = createAppSlice({
name: 'test',
initialState: [],
reducers: (create) => ({
thunkReducers: create.asyncThunk(
function payloadCreator(arg, api) {
return Promise.resolve('resolved payload')
},
{ pending, fulfilled, settled },
),
}),
})
expect(slice.caseReducers.thunkReducers.pending).toBe(pending)
expect(slice.caseReducers.thunkReducers.fulfilled).toBe(fulfilled)
expect(slice.caseReducers.thunkReducers.settled).toBe(settled)
// even though it is not defined above, this should at least be a no-op function to match the TypeScript typings
// and should be callable as a reducer even if it does nothing
expect(() =>
slice.caseReducers.thunkReducers.rejected(
[],
slice.actions.thunkReducers.rejected(
new Error('test'),
'fakeRequestId',
),
),
).not.toThrow()
})
test('can define reducer with prepare statement using create.preparedReducer', async () => {
const slice = createSlice({
name: 'test',
initialState: [] as any[],
reducers: (create) => ({
prepared: create.preparedReducer(
(p: string, m: number, e: { message: string }) => ({
payload: p,
meta: m,
error: e,
}),
(state, action) => {
state.push(action)
},
),
}),
})
expect(
slice.reducer(
[],
slice.actions.prepared('test', 1, { message: 'err' }),
),
).toMatchInlineSnapshot(`
[
{
"error": {
"message": "err",
},
"meta": 1,
"payload": "test",
"type": "test/prepared",
},
]
`)
})
test('throws an error when invoked with a normal `prepare` object that has not gone through a `create.preparedReducer` call', async () => {
expect(() =>
createSlice({
name: 'test',
initialState: [] as any[],
reducers: (create) => ({
prepared: {
prepare: (p: string, m: number, e: { message: string }) => ({
payload: p,
meta: m,
error: e,
}),
reducer: (state, action) => {
state.push(action)
},
},
}),
}),
).toThrowErrorMatchingInlineSnapshot(
`[Error: Please use the \`create.preparedReducer\` notation for prepared action creators with the \`create\` notation.]`,
)
})
})
})
|