redux thunk - TypeScript, react-testning saknar typ i AnyAction
Jag får det här felet:
TS2345: Argument of type '(dispatch: Dispatch) => Promise<void>' is not assignable to parameter of
type 'AnyAction'. Property 'type' is missing in type '(dispatch: Dispatch) => Promise<void>' but
required in type 'AnyAction'. type' is declared here* :
* Koden för deklarationen är:
export interface Action<T = any> {
type: T
}
AnyAction utökar Action.
Detta är min kod på testet:
import configureStore from 'redux-mock-store';
import reduxThunk from 'redux-thunk';
// some code, then in the test I have:
const mockStore = configureStore([reduxThunk]);
const store = mockStore({});
store.dispatch(signIn()); //here I have the error
Definitionen av signIn är:
export const signIn = () =>
async (dispatch: Dispatch): Promise<void> => {
dispatch({
type: SIGN_IN_REQUEST
});
};
Någon ledtråd eller idé om hur man fixar det?
Svar #1
configureStore tillåter oss att skicka argument till express dispatch-tillägg, så för att få det att fungera med redux-thunk måste vi specificera ThunkDispatch som argument enligt följande:
import { ThunkDispatch } from 'redux-thunk';
// your app state
interface AppState {}
// you can even express more params for `ThunkDispatch`
const mockStore = configureMockStore<AppState, ThunkDispatch<AppState, any, any>>([])
Svar #2
Som tmho2005 sa, gjorde jag det genom att läsa hans svar och en annan liknande tråd. Detta är min kod ifall någon vill ha den:
// only relevant code for the question
import { AnyAction } from 'redux';
import configureStore from 'redux-mock-store';
import reduxThunk, { ThunkDispatch } from 'redux-thunk';
import { AuthState } from '../../../types'; // that's the definition of my app state
type DispatchExts = ThunkDispatch<AuthState, void, AnyAction>;
// And the code for mys tests:
const mockStore = configureStore<AuthState, DispatchExts>([reduxThunk]);
const store = mockStore(defaultState);
await store.dispatch(signIn({
username: 'foo',
password: 'bar'
}));
