打字稿,单元测试:正确键入以使用redux-mock-store中的store.dispatch调度Thunk

时间:2018-10-04 13:54:53

标签: typescript unit-testing redux redux-mock-store

有什么方法可以从redux-mock-store创建的商店中正确调度Thunk吗?现在我被迫使用任何类型断言

store.dispatch<any>(getCommissions());

dispatch希望提供简单的操作

[ts]
Argument of type '(dispatch: ThunkDispatch<IRootState, undefined, 
AnyAction>, getState: () => IRootState) => void' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type '(dispatch: ThunkDispatch<IRootState, undefined, AnyAction>, getState: () => IRootState) => void'.

getCommisions()的代码片段

export function getCommissions() {
  return (dispatch: ThunkDispatch<IRootState, undefined, AnyAction>, getState: () => IRootState) => { ... }

3 个答案:

答案 0 :(得分:2)

默认导出为createMockStore的{​​{1}}函数接受通用类型redux-mock-store,其中<S, DispatchExts>是Redux状态的定义,而S是任何添加的Redux中间件的(或单个)附加DispatchExts签名的并集。

因此,进行此设置的方法是从Dispatch导入ThunkDispatch,后者接受自己的redux-thunk通用参数,并将其作为<State, ExtraArgument, Action>参数传递给DispatchExts

这是一个简短的示例:

createMockStore

希望对您有帮助!

我当前的版本: import { AnyAction } from 'redux'; // Or your own Action definition import createMockStore from 'redux-mock-store'; import thunk, { ThunkDispatch } from 'redux-thunk'; import { ApplicationState } from '../your/definitions'; type DispatchExts = ThunkDispatch<ApplicationState, void, AnyAction>; const middleware = [thunk]; const mockStore = createMockStore<ApplicationState, DispatchExts>(middleware); const store = mockStore(); redux 4.0.0 redux-thunk 2.3.0 redux-mock-store 1.5.3

typescript 2.9.2的定义https://github.com/reduxjs/redux-thunk/blob/master/index.d.ts

ThunkDispatch定义https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/redux-mock-store/index.d.ts

答案 1 :(得分:2)

对于configureMockStore使用,解决方案几乎与上面完全相同。

import configureMockStore from 'redux-mock-store';
import thunk, { ThunkDispatch } from 'redux-thunk';
import { MyState, MyActions } from './my-types';

type DispatchExts = ThunkDispatch<MyState, undefined, MyActions>;

const middlewares = [thunk];
const mockStore = configureMockStore<MyState, DispatchExts>(middlewares);

const store = mockStore();

使用redux 4.0.1 redux-thunk 2.3.0 redux-mock-store 1.5.3typescript 3.5.3的两个示例

答案 2 :(得分:0)

在类似的情况下,我发现了用Typescript编写的库的最新版本,并且与redux(4.0.4)和redux-thunk 2.3.0的最新版本一起使用时效果更好。

https://github.com/jedmao/redux-mock-store