reactjs - 测试自定义 Hook : Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

标签 reactjs redux jestjs react-testing-library

我有一个想要测试的自定义 Hook 。它接收一个 redux 存储调度函数并返回一个函数。为了得到我想要做的结果:

const { result } = renderHook(() => { useSaveAuthenticationDataToStorages(useDispatch())});

但是,我收到错误:

Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a

发生这种情况是因为 useDispatch 并且没有连接存储。但是,我这里没有任何组件可以与提供程序一起包装。我只需要测试只是将数据保存到存储的钩子(Hook)。

如何修复它?

最佳答案

react hooks 测试库 docs对此进行更深入的探讨。然而,我们本质上缺少的是我们可以通过创建包装器来获得的提供者。首先我们声明一个组件作为我们的提供者:

import { Provider } from 'react-redux'

const ReduxProvider = ({ children, reduxStore }) => (
  <Provider store={reduxStore}>{children}</Provider>
)

然后在我们的测试中我们调用

test("...", () => {
  const store = configureStore();
  const wrapper = ({ children }) => (
    <ReduxProvider reduxStore={store}>{children}</ReduxProvider>
  );
  const { result } = renderHook(() => {
    useSaveAuthenticationDataToStorages(useDispatch());
  }, { wrapper });
  // ... Rest of the logic
});

关于reactjs - 测试自定义 Hook : Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a <Provider>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59476912/

相关文章:

react-native - react 原生 redux 连接未定义的函数

javascript - 更新特征数组的特定对象

javascript - 应用 API 响应转换的最佳位置

unit-testing - 在 Jest 中,当使用函数生成 describe/it block 时,有没有办法让 beforeAll/beforeEach block 在断言之前运行?

jestjs - 如何清除 Jest 缓存?

javascript - 在 ImmutableJS 中用 Iterable 替换 Map

javascript - react 测试 Hook 状态是否被子组件更新

javascript - react 路由器 onEnter 错误

javascript - react 原生中可能出现未处理的 promise 拒绝

jasmine - 是否有忽略 jest.js 中元素位置的数组相等匹配函数?