代码之家  ›  专栏  ›  技术社区  ›  pmiranda

TypeScript,react测试AnyAction中缺少的类型

  •  1
  • pmiranda  · 技术社区  · 4 年前

    我有个错误:

    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* :
    

    * 声明的代码是:

    export interface Action<T = any> {
      type: T
    }
    

    这是我的测试代码:

    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
    

    的定义 signIn 是:

    export const signIn = () =>
      async (dispatch: Dispatch): Promise<void> => {
        dispatch({
          type: SIGN_IN_REQUEST
        });
      };
    

    有什么关于如何修复它的提示或想法?

    2 回复  |  直到 4 年前
        1
  •  2
  •   tmhao2005    4 年前

    configureStore 允许我们传递参数来表示调度扩展,以便使其工作 redux-thunk 我们必须具体说明 ThunkDispatch 作为参数如下:

    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>>([])
    
        2
  •  0
  •   pmiranda    4 年前

    正如tmho2005所说,我是通过阅读他的答案和其他类似的线索来做到这一点的。这是我的代码,以防有人想要它:

    // 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'
    }));