【问题标题】:TypeScript, react testing missing type in AnyActionTypeScript,在 AnyAction 中反应测试缺少的类型
【发布时间】:2021-02-23 01:37:19
【问题描述】:

我遇到了这个错误:

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
}

AnyAction 扩展了 Action。

这是我的测试代码:

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

关于如何修复它的任何提示或想法?

【问题讨论】:

    标签: typescript redux-thunk react-testing-library


    【解决方案1】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-09-15
        • 2021-07-30
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        • 2019-11-19
        • 2015-12-02
        • 2019-02-07
        • 1970-01-01
        相关资源
        最近更新 更多