打字稿,单元测试:使用redux-mock-store发送store.dispatch的正确键入



有没有办法从使用 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) => { ... }

作为redux-mock-store默认导出的createMockStore函数接受泛型类型<S, DispatchExts>其中S是 Redux 状态的定义,DispatchExts是任何添加的 Redux 中间件的(或单个(附加Dispatch签名的联合。

所以设置它的方法是从redux-thunk导入ThunkDispatch,它接受自己的泛型<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.0redux-thunk 2.3.0redux-mock-store 1.5.3typescript 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

对于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();

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

在类似的情况下,我发现了用 Typescript 编写的库的最新分支,并且可以更好地与最新版本的 redux (4.0.4( 和 redux-thunk2.3.0一起使用。

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

相关内容

  • 没有找到相关文章

最新更新