ady*_*yry 5 unit-testing typescript redux redux-mock-store
有什么方法可以从redux-mock-store创建的商店中正确调度Thunk吗?现在我被迫使用任何类型断言
store.dispatch<any>(getCommissions());
Run Code Online (Sandbox Code Playgroud)
如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'.
Run Code Online (Sandbox Code Playgroud)
的代码片段 getCommisions()
export function getCommissions() {
return (dispatch: ThunkDispatch<IRootState, undefined, AnyAction>, getState: () => IRootState) => { ... }
Run Code Online (Sandbox Code Playgroud)
小智 9
createMockStore默认导出的函数redux-mock-store接受通用类型<S, DispatchExts>,其中S是您的Redux状态的定义,DispatchExts是Dispatch任何添加的Redux中间件的(或单个)附加签名的并集。
因此,设置此方式是导入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();
Run Code Online (Sandbox Code Playgroud)
希望对您有帮助!
我当前的版本:
redux 4.0.0
redux-thunk 2.3.0
redux-mock-store 1.5.3
typescript 2.9.2
ThunkDispatch定义https://github.com/reduxjs/redux-thunk/blob/master/index.d.ts
createMockStore定义https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/redux-mock-store/index.d.ts
小智 7
对于configureMockStore使用,解决方案几乎与@nickpassarella 的答案完全相同。
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();
Run Code Online (Sandbox Code Playgroud)
两个示例都使用redux 4.0.1 redux-thunk 2.3.0 redux-mock-store 1.5.3和typescript 3.5.3