typescript ,单元测试 : Correct typing for Dispatching a Thunk with store. 从 redux-mock-store 发送

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

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

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

因为 dispatch 期望提供简单的 Action

[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) => { ... }

最佳答案

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

希望对你有帮助!

我当前的版本: 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

关于 typescript ,单元测试 : Correct typing for Dispatching a Thunk with store. 从 redux-mock-store 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52648553/

相关文章:

typescript - Azure AD - MSAL.js - ssoSilent() 与 acquireTokenSilent()

javascript - React 单元测试 onClick 方法中的 Mock Fetch API

javascript - React 组件事件处理函数未从 Redux Store 接收到最新值

javascript - Flow with redux - 传递联合类型会出错

reactjs - Redux reducer 设计

arrays - 在 TypeScript 中向类型化数组添加方法

javascript - Angular 2 中的 Leaflet + Google - 瓷砖顺序错误

angular - 在垫选择上过滤

reactjs - 如何在 Enzyme React 测试中访问嵌套组件

c# - .NET 单元测试可以使用哪种动态语言?