Spaces:
Running
Running
File size: 2,595 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 | import type { Context } from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import type { Action, Middleware, UnknownAction } from 'redux'
import type { ThunkDispatch } from 'redux-thunk'
import { createDynamicMiddleware } from '../react'
interface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {
(n: 1): 1
}
const untypedInstance = createDynamicMiddleware()
const typedInstance = createDynamicMiddleware<number, AppDispatch>()
declare const compatibleMiddleware: Middleware<{}, number, AppDispatch>
declare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>
declare const customContext: Context<ReactReduxContextValue | null>
declare const addedMiddleware: Middleware<(n: 2) => 2>
describe('type tests', () => {
test('instance typed at creation enforces correct middleware type', () => {
const useDispatch = typedInstance.createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const createDispatchWithMiddlewareHook =
typedInstance.createDispatchWithMiddlewareHookFactory(customContext)
const useDispatchWithContext = createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
})
test('withTypes() enforces correct middleware type', () => {
const createDispatchWithMiddlewareHook =
untypedInstance.createDispatchWithMiddlewareHook.withTypes<{
state: number
dispatch: AppDispatch
}>()
const useDispatch = createDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
const createCustomDispatchWithMiddlewareHook = untypedInstance
.createDispatchWithMiddlewareHookFactory(customContext)
.withTypes<{
state: number
dispatch: AppDispatch
}>()
const useCustomDispatch = createCustomDispatchWithMiddlewareHook(
compatibleMiddleware,
// @ts-expect-error
incompatibleMiddleware,
)
})
test('useDispatchWithMW returns typed dispatch, with any applicable extensions', () => {
const useDispatchWithMW =
typedInstance.createDispatchWithMiddlewareHook(addedMiddleware)
const dispatch = useDispatchWithMW()
// standard
expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()
// thunk
expectTypeOf(dispatch(() => 'foo')).toBeString()
// static
expectTypeOf(dispatch(1)).toEqualTypeOf<1>()
// added
expectTypeOf(dispatch(2)).toEqualTypeOf<2>()
})
})
|