|
| 1 | +import type { Action, ThunkAction } from '@reduxjs/toolkit' |
| 2 | +import { configureStore, createAsyncThunk, createSlice } from '@reduxjs/toolkit' |
| 3 | +import { injectDispatch, injectSelector, injectStore } from "../public-api" |
| 4 | + |
| 5 | +export interface CounterState { |
| 6 | + counter: number |
| 7 | +} |
| 8 | + |
| 9 | +const initialState: CounterState = { |
| 10 | + counter: 0, |
| 11 | +} |
| 12 | + |
| 13 | +export const counterSlice = createSlice({ |
| 14 | + name: 'counter', |
| 15 | + initialState, |
| 16 | + reducers: { |
| 17 | + increment(state) { |
| 18 | + state.counter++ |
| 19 | + }, |
| 20 | + }, |
| 21 | +}) |
| 22 | + |
| 23 | +export function fetchCount(amount = 1) { |
| 24 | + return new Promise<{ data: number }>((resolve) => |
| 25 | + setTimeout(() => resolve({ data: amount }), 500), |
| 26 | + ) |
| 27 | +} |
| 28 | + |
| 29 | +export const incrementAsync = createAsyncThunk( |
| 30 | + 'counter/fetchCount', |
| 31 | + async (amount: number) => { |
| 32 | + const response = await fetchCount(amount) |
| 33 | + // The value we return becomes the `fulfilled` action payload |
| 34 | + return response.data |
| 35 | + }, |
| 36 | +) |
| 37 | + |
| 38 | +const { increment } = counterSlice.actions |
| 39 | + |
| 40 | +const counterStore = configureStore({ |
| 41 | + reducer: counterSlice.reducer, |
| 42 | +}) |
| 43 | + |
| 44 | +type AppStore = typeof counterStore |
| 45 | +type AppDispatch = typeof counterStore.dispatch |
| 46 | +type RootState = ReturnType<typeof counterStore.getState> |
| 47 | +type AppThunk<ThunkReturnType = void> = ThunkAction< |
| 48 | + ThunkReturnType, |
| 49 | + RootState, |
| 50 | + unknown, |
| 51 | + Action |
| 52 | +> |
| 53 | + |
| 54 | +describe('injectSelector.withTypes<RootState>()', () => { |
| 55 | + test('should return injectSelector', () => { |
| 56 | + const injectAppSelector = injectSelector.withTypes<RootState>() |
| 57 | + |
| 58 | + expect(injectAppSelector).toBe(injectSelector) |
| 59 | + }) |
| 60 | +}) |
| 61 | + |
| 62 | +describe('injectDispatch.withTypes<AppDispatch>()', () => { |
| 63 | + test('should return injectDispatch', () => { |
| 64 | + const injectAppDispatch = injectDispatch.withTypes<AppDispatch>() |
| 65 | + |
| 66 | + expect(injectAppDispatch).toBe(injectDispatch) |
| 67 | + }) |
| 68 | +}) |
| 69 | + |
| 70 | +describe('injectStore.withTypes<AppStore>()', () => { |
| 71 | + test('should return injectStore', () => { |
| 72 | + const injectAppStore = injectStore.withTypes<AppStore>() |
| 73 | + |
| 74 | + expect(injectAppStore).toBe(injectStore) |
| 75 | + }) |
| 76 | +}) |
0 commit comments