react-mock-store:类型错误:中间件不是函数

问题描述 投票:0回答:1

我正在将 jest 与 React 和 TypeScript 结合使用。

import configureStore from "redux-mock-store";
import thunk from "redux-thunk";

const mockStore = configureStore([thunk]);

  it("should handle fetchCharacterDataAsync", async () => {
    const characterInitialState = {
      data: null,
      isLoading: false,
      error: undefined,
    };
    const store = mockStore(characterInitialState);
    await store.dispatch(fetchCharacterDataAsyncTHUNK("1011334") as any);
  });

我正在尝试模拟react-redux-store并添加thunk作为中间件,以便我可以从我的商店发送thunk。

遵循react-mock-store文档,但似乎无法将thunks中间件传递给configureStore()。当我这样做时(就像我上面所做的那样),我收到错误:

类型 'typeof import("random_path/redux-thunk/dist/redux-thunk")' 不可分配给类型 'Middleware<{}, any, Dispatch>'。 类型 'typeof import("random_path/redux-thunk/dist/redux-thunk")' 与签名 '(api: MiddlewareAPI): (next: Dispatch) => (action: any) => any' 不匹配.

所以为了绕过这个我正在这样做:

const mockStore = configureStore([thunk as any]); 

但是,这给了我:

类型错误:中间件不是函数

文档在这里:https://github.com/reduxjs/redux-mock-store 这应该有效,因为我遵循了他们的要求......!?

非常感谢任何帮助:)

reactjs typescript react-redux jestjs
1个回答
0
投票

我怀疑您正在使用当前版本 3 的

thunk
,其中不再有默认导出。
thunk
thunk@3
中的命名导出。

导入 named

thunk
导出。

import configureStore from "redux-mock-store";
import { thunk } from "redux-thunk";

const mockStore = configureStore([thunk]);

it("should handle fetchCharacterDataAsync", async () => {
  const characterInitialState = {
    data: null,
    isLoading: false,
    error: undefined,
  };
  const store = mockStore(characterInitialState);
  await store.dispatch(fetchCharacterDataAsyncTHUNK("1011334") as any);
});

也就是说,使用

redux-mock-store
实际上被认为是一种过时的做法,您应该在单元测试中实例化并使用实际的 Redux 存储。 Redux-Toolkit
configureStore
已经包含默认启用的 Thunk 中间件。

示例:

import { configureStore } from "@reduxjs/toolkit";
import { rootReducer } from "../path/to/rootReducer";

it("should handle fetchCharacterDataAsync", async () => {
  const characterInitialState = {
    data: null,
    isLoading: false,
    error: undefined,
  };

  const store = configureStore({
    reducer: rootReducer,
    preloadedState: characterInitialState,
  });

  await store.dispatch(fetchCharacterDataAsyncTHUNK("1011334"));

  // ...assertions
});
© www.soinside.com 2019 - 2024. All rights reserved.